How to determine whether object reference is null?
Asked Answered
K

5

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
}
Kino answered 17/8, 2012 at 5:26 Comment(1)
If you want to default to something, you can always do MyObject obj = myObjVar ?? DefaultObjVarJaquesdalcroze
S
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.

Sumba answered 17/8, 2012 at 5:29 Comment(0)
R
8

You can use Object.ReferenceEquals

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

This would return true, if the myObjVar is null.

Reimpression answered 17/8, 2012 at 5:45 Comment(2)
This is useful if you want to override the == operator for an object.Eau
If you happen to be wanting to test for null inside your implementation of == then I think Object.ReferenceEquals is essential.Boutonniere
C
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();
Chiccory answered 17/8, 2012 at 5:29 Comment(1)
I think that the null-coalescing operator was introduced in C# 2Fisch
L
3

you can:

MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar)) 
{
    // do stuff
}
Lute answered 17/8, 2012 at 5:34 Comment(1)
why the need for two if statements?Reversible
S
0

In C# 7.0 you can use is null:

MyObject myObjVar = null;
if (myObjVar is null)
{
    // do stuff
}
Stratiform answered 14/7, 2021 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.