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'?


您可以通过运算符在C#中获得相同的语法:

  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
    ...
  }

C# language philosophy is quite different than that of JavaScript. C# usually forces you to be more explicit about somethings in order to prevent some common programming errors (and I'm sure this also helps simplify the compiler design & test).

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

if(myobject = otherObject)
{
   ...
}

where you've made an assignment instead of an equality check. Normally C# prevents such mistakes (so although Dmitry's answer is clever, I'd advise against it).


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

 var myobject = notNullValue ?? nullValue;
链接地址: http://www.djcxy.com/p/76364.html

上一篇: 使用jQuery检查值是否为null

下一篇: 最短的空检查在C#