13

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
}
CJ7
  • 22,579
  • 65
  • 193
  • 321

5 Answers5

10

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.

Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
8

You can use Object.ReferenceEquals

if (Object.ReferenceEquals(null, myObjVar)) 
{
   ....... 
} 

This would return true, if the myObjVar is null.

Mohan Kumar
  • 6,008
  • 6
  • 28
  • 36
7

The way you are doing is the best way

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

but you can use null-coalescing operator ?? to check, as well as assign something

var obj  = myObjVar ?? new MyObject();
Habib
  • 219,104
  • 29
  • 407
  • 436
3

you can:

MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar)) 
{
    // do stuff
}
Habib Zare
  • 1,206
  • 8
  • 17
0

In C# 7.0 you can use is null:

MyObject myObjVar = null;
if (myObjVar is null)
{
    // do stuff
}
Misha Zaslavsky
  • 8,414
  • 11
  • 70
  • 116