Dave Sumter Dave Sumter - 1 month ago 10
C# Question

Shortest null check in c#

Is there a shorter way to write this in c#:

if(myobject!=null){

}


In JavaScript we can do this:

if(myobject){

}


Disclaimer: I know this will match 'true' as well in JavaScript. This would only be used on variables that should be a specific type of object.

I found some similar questions, but they're asking slightly different things:

C# Shortest Way to Check for Null and Assign Another Value if Not

Best and fastest way to check if an object is null

How to determine if variable is 'undefined' or 'null'?

Answer Source

You can obtain the same syntax in C# via operator:

  public class MyClass {
    ...
    // True if instance is not null, false otherwise
    public static implicit operator Boolean(MyClass value) {
      return !Object.ReferenceEquals(null, value);  
    }   
  }


....

  MyClass myobject = new MyClass();
  ...
  if (myobject) { // <- Same as in JavaScript
    ...
  }