How does one check if an object's reference is NULL?

  • Thread starter Thread starter Karen Hill
  • Start date Start date
K

Karen Hill

How does one check if an object's reference is null? I'd like to check
that rather than catch a nullreference exception.

thanks.
 
if(obj == null)
{
// it's null
}
else
{
// it's not null
}

HTH

Simon.
 
Karen,

If you have a variable, you can just use the equality operator, like so:

// The variable declaration.
MyClass instance = ...

To check to see if the variable is null, you do this:

if (instance == null)
{
// Code that executes when a variable is null is put here.
}

Hope this helps.
 
Karen,

You're probably better off using ReferenceEquals(obj, null). This will
always work. The equality operator (==) could be overloaded and might
be checking if the values are equal instead of the references, so
ReferenceEquals() is a safer bet.

-Craig
 
You're probably better off using ReferenceEquals(obj, null). This will
always work. The equality operator (==) could be overloaded and might
be checking if the values are equal instead of the references, so
ReferenceEquals() is a safer bet.

Any overload of == worth its salt should check for nullity anyway. I
believe that using == is more readable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top