CJ7
CJ7

Reputation: 23275

How to determine whether object reference is null?

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
}

Upvotes: 13

Views: 57023

Answers (5)

Misha Zaslavsky
Misha Zaslavsky

Reputation: 9646

In C# 7.0 you can use is null:

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

Upvotes: 0

Habib Zare
Habib Zare

Reputation: 1204

you can:

MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar)) 
{
    // do stuff
}

Upvotes: 3

Mohan Kumar
Mohan Kumar

Reputation: 6056

You can use Object.ReferenceEquals

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

This would return true, if the myObjVar is null.

Upvotes: 8

Habib
Habib

Reputation: 223257

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();

Upvotes: 7

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174319

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.

Upvotes: 10

Related Questions