Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I detect a null reference in C#?

Tags:

c#

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.

like image 949
Fred Avatar asked Nov 27 '22 23:11

Fred


2 Answers

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.

like image 53
Robert Paulson Avatar answered Jan 16 '23 22:01

Robert Paulson


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();
}
like image 24
Joel Coehoorn Avatar answered Jan 16 '23 21:01

Joel Coehoorn