5

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

Community
  • 1
  • 1
Dave Sumter
  • 2,926
  • 1
  • 21
  • 29
  • 1
    You can do a lot of things in JavaScript that are inadvisable and which C# simply prohibits. That's one of them (there's already plenty of discussion on the web as to _why_ that's inadvisable, so I won't belabor that point). – Peter Duniho Oct 31 '14 at 07:01
  • you can write your own ifNull() function and even make it shorter by calling it ifN().. – TaW Oct 31 '14 at 08:07
  • 1
    Why the downvote..? It's a legitimate question isn't it..? – Dave Sumter Oct 31 '14 at 08:50

5 Answers5

12

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
    ...
  }
Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Although this is the only way to achieve a shorter `null` check IMHO, this works only for your own classes, unfortunately. – fero Oct 31 '14 at 07:06
  • Works like a charm! Just a note, I had to make it static too.. eg. public static implicit operator ... – Dave Sumter Oct 31 '14 at 07:29
  • @fero You could write an `IsNull(this object o)` extension method and then use it as `if (someObject.IsNull())`. This would work for any object. Question is whether it is that much shorter... – Thorsten Dittmar Oct 31 '14 at 11:52
8

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

Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
2

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

 var myobject = notNullValue ?? nullValue;
Ramgy Borja
  • 2,330
  • 2
  • 19
  • 40
0

If you want to Throw an ArgumentNullException e.g. to check method parameters, there is a handy one-liner to do this:

_ = x ?? throw new ArgumentNullException(nameof(x));

Here, we try to assign the parameter to the discard _ operator. The ??-operator performs a nullcheck. If the variable is null, the exception is thrown.

In Visual Studio you can add a custom snippet to bind this line to the shortcut arg0. You only need to type arg0, double press the TAB key, and to type the parameter name. Implementing a null check then only takes 2 seconds.

Here is the snippet. To import it into Visual Studio, please use this guide: https://learn.microsoft.com/de-de/visualstudio/ide/walkthrough-creating-a-code-snippet?view=vs-2019

<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
    <Header>
        <Title>Argument null check for parameters</Title>
        <Shortcut>arg0</Shortcut>
    </Header>
    <Snippet>
        <Code Language="CSharp">
            <![CDATA[_= $param$ ?? throw new ArgumentNullException(nameof($param$));]]>
        </Code>
        <Declarations>
            <Literal>
                <ID>param</ID>
                <ToolTip>Name of the parameter.</ToolTip>
                <Default>x</Default>
            </Literal>
        </Declarations>
    </Snippet>
</CodeSnippet>

derMrich
  • 316
  • 4
  • 12
-6

You can use object class static method ReferenceEquals method to find out if the refrence is null or not

  MyClass1 obj = new MyClass1();
        if (object.ReferenceEquals(obj,null))
        {
            Console.Write("obj ref is null");
        }
Numan Hanif
  • 246
  • 2
  • 17
  • 1
    `object.ReferenceEquals(obj,null)` is not shorter than `obj == null`. In fact, I'd argue it's quite a bit longer. – Corak Oct 31 '14 at 07:23