How to determine whether object reference is null?

CJ7 picture CJ7 · Aug 17, 2012 · Viewed 54.5k times · Source

What is the best way to determine whether an object reference variable is null?

Is it the following?

MyObject myObjVar = null;
if (myObjVar == null)
{
    // do stuff
}

Answer

Daniel Hilgarth picture Daniel Hilgarth · Aug 17, 2012

Yes, you are right, the following snippet is the way to go if you want to execute arbitrary code:

MyObject myObjVar; 
if (myObjVar == null) 
{ 
    // do stuff 
} 

BTW: Your code wouldn't compile the way it is now, because myObjVar is accessed before it is being initialized.