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 and JavaScript. This will only be used for variables that must be a specific type of object.

I found several similar questions, but they ask slightly different things:

C # Shortest way to check for null and assign a different value if not

Best and fastest way to check if an object is null

How do I determine if a variable is "undefined" or "null"?

+3


source to share


4 answers


You can get the same syntax in C # with the 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
    ...
  }

      

+11


source


The philosophy of C # is not at all like JavaScript. C # tends to force you to be more explicit about certain cases in order to prevent some common programming mistakes (and I'm sure it makes compiler development and testing easier as well).

If C # allows such an implicit conversion to boolean, you are more likely to run into programming errors like this:



if(myobject = otherObject)
{
   ...
}

      

where you did the job instead of checking equality. Usually C # prevents such errors (so although Dmitry's answers are smarter, I would recommend that).

+8


source


used ?? Operator https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-conditional-operator

 var myobject = notNullValue ?? nullValue;

      

+1


source


With ReferenceEquals method you can use static method of object class to find out if refrence is null or not

  MyClass1 obj = new MyClass1();
        if (object.ReferenceEquals(obj,null))
        {
            Console.Write("obj ref is null");
        }

      

-five


source







All Articles