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
}
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
}
You can use Object.ReferenceEquals
This would return true, if the myObjVar is null.
Yes, you are right, the following snippet is the way to go if you want to execute arbitrary code:
BTW: Your code wouldn't compile the way it is now, because
myObjVar
is accessed before it is being initialized.you can:
The way you are doing is the best way
but you can use null-coalescing operator
??
to check, as well as assign something