Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 682
Dave Sumter Avatar asked Oct 31 '14 06:10

Dave Sumter


People also ask

Does .ANY check for null?

Any() internally attempts to access the underlying sequence ( IEnumerable ). Since the object can be null, there is no way to access the enumerable to validate it, hence a NullReferenceException is thrown to indicate this behavior.

IS null check C#?

The String class in the System namespace provides the IsNullOrEmpty() method to check if a string is null or an empty string(""). This is a handy method to validate user input.

IS null check necessary?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.


3 Answers

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
    ...
  }
like image 165
Dmitry Bychenko Avatar answered Oct 02 '22 02:10

Dmitry Bychenko


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

like image 25
Eren Ersönmez Avatar answered Oct 02 '22 02:10

Eren Ersönmez


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

 var myobject = notNullValue ?? nullValue;
like image 26
Ramgy Borja Avatar answered Oct 02 '22 02:10

Ramgy Borja