Fred Fred - 1 year ago 114
C# Question

How do I detect a null reference in 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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download