Question: Object Reference not set to an instance of an object.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi Guys,

been puzzled with this error for few days now. In the try and catch block, i
am trying to set the label text property to property retrieved from exchange
database. The record has certain properties set and some are not. I keep on
getting error Object reference not set to an instance of an object...

here is my code
if(!indvContact.Surname.Equals(null))
{
surname.Text=indvContact.Surname.ToString();
}
I assumed that it will work however it dont. Is there any way in the catch
block, i can tell the code to move on to the next step ...or maybe another
approach to it..

Thanks
 
I think you should first learn what it means for an object to be null.

if the Surname property is null - then accessing its Equals method is going
to fail - because the property is null! And 'null' does not have an Equals
method. So in cases where Surname is null, this call fails.

I am not sure why it would even occur to you to check for null this way?
This should be done:

if (!indvContact.Surname == null)
{
}
 
Thanks Mariana, i will try this.

Marina said:
I think you should first learn what it means for an object to be null.

if the Surname property is null - then accessing its Equals method is going
to fail - because the property is null! And 'null' does not have an Equals
method. So in cases where Surname is null, this call fails.

I am not sure why it would even occur to you to check for null this way?
This should be done:

if (!indvContact.Surname == null)
{
}
 
Actually, there are two possibilities of null objects in the code, either of
which would throw the same error:

Object References:
indvContact
surname

indvContact.Surname is also an Object Reference, but it is used in the first
part to see whether it is null, which would not throw an exception, unless
indvContact itself is null.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Neither a follower nor a lender be.
 
Back
Top