If statement with a null check

I'm doing a null check for this object.

if (Myobject.EndofLife.Status == true) {
       //do some
}

When, 'EndofLife' property is null, we receive a 'Object reference' error.

So, modified to something like

if (Myobject.EndofLife != null && Myobject.EndofLife.Status == true)`

I can't seem to be using fancy operator here, like ?. or null coalescing operator (??).

Are there any fancy operators here (instead of my null check above)

Upvotes: 2

Views: 1208

Answers (3)

Matt
Matt

Reputation: 27026

You can do:

    MyClass MyObject = null; // assuming the object wasn't instantiated
    if ((MyObject?.EndOfLife?.Status) ?? false == true)
    {
        // do something
    }

The expresseion

    ((MyObject?.EndOfLife?.Status) ?? false)

also covers the case when MyObject was instantiated, but EndOfLife wasn't, i.e.

     MyClass MyObject = new MyClass(); // EndOfLife is null

As you can see, it avoids Nullreference-Exceptions and it assumes false if any objects are null - so, if either  MyObject is null  or  EndOfLife is null,  then the code will  not  throw an exception.

Provided the classes you defined are like:

class MyClass
{
    public EndOfLifeInfo EndOfLife { get; set; }
}

public class EndOfLifeInfo
{
    public bool Status { get; set; }
}

Note: As @oerkelens mentioned correctly, == true is redundant and can be removed, but for understanding the code it is easier to read.

Upvotes: 1

VirtualRiddles
VirtualRiddles

Reputation: 11

Try this:

if (Myobject?.EndofLife?.Status ?? false) {
    //do some
}

Upvotes: 1

gidanmx2
gidanmx2

Reputation: 469

Starting from C# 6 there is the Monadic null checking, so you can write:

if (Myobject.EndofLife?.Status == true) {

Upvotes: 3

Related Questions