How to determine whether object reference is null?

2020-08-09 11:00发布

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
}

4条回答
聊天终结者
2楼-- · 2020-08-09 11:37

You can use Object.ReferenceEquals

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

This would return true, if the myObjVar is null.

查看更多
孤傲高冷的网名
3楼-- · 2020-08-09 11:55

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.

查看更多
对你真心纯属浪费
4楼-- · 2020-08-09 11:55

you can:

MyObject myObjVar = MethodThatMayOrMayNotReturnNull();
if (if (Object.ReferenceEquals(null, myObjVar)) 
{
    // do stuff
}
查看更多
虎瘦雄心在
5楼-- · 2020-08-09 11:57

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();
查看更多
登录 后发表回答