How do I determine if an object reference is null in C# w/o throwing an exception if it is null?
i.e. If I have a class reference being passed in and I don't know if it is null or not.
testing against null will never* throw an exception
void DoSomething( MyClass value )
{
if( value != null )
{
value.Method();
}
}
* never as in should never. As @Ilya Ryzhenkov points out, an incorrect implementation of the != operator for MyClass could throw an exception. Fortunately Greg Beech has a good blog post on implementing object equality in .NET.
What Robert said, but for that particular case I like to express it with a guard clause like this, rather than nest the whole method body in an if block:
void DoSomething( MyClass value )
{
if ( value == null ) return;
// I might throw an ArgumentNullException here, instead
value.Method();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With