Handy C# Shortcuts

Rather than walking down an object model validating that each level is not null, like this:

if ((this.MyThing != null) && (this.MyThing.MySubThing != null))
{
    // do stuff
}

You can shortcut with a Null-conditional Operator:

if (this.MyThing?.MySubThing != null)
{
    // do stuff
}

Rather than explicitly checking and initializing a backing variable, like this:

public Thing MyThing
{
    get
    {
        if (_myThing == null)
        {
            _myThing = new Thing();
        }
        return _myThing;
    }
    set { _myThing = value; }
}

You can use a Null-coalescing Operator and make use of the fact that assigning a value to a variable also returns the value:

public Thing MyThing
{
    get { return _myThing ?? (_myThing = new Thing()); }
    set { _myThing = value; }
}

Rather than creating a read-only property without a setter, like this:

public Thing MyOtherThing
{
    get
    {
        return _myOtherThing;
    }
}

You can just use a Lambda Operator to return the backing variable:

public Thing MyOtherThing => _myOtherThing;
Advertisements