Check for null and assign to a variable at once in C# 8

Viewed 2486

Probably a trivial question, but I'm trying to get up to date with modern C# and I am overwhelmed with all the new features like pattern matching etc.

With C# 8, is there a new way to simplify the following common pattern, were I check a property for being non null and if so, store it in a var for use within the if scope? That is:

var item = _data.Item;
if (item != null)
{ 
    // use item
}

I could think of this:

if (_data.Item is var item && item != null)
{ 
    // use item
}

And this:

if (_data.Item is Item item)
{ 
    // use item
}

Between these, I'd still pick the 1st snippet.

3 Answers

Also you can use empty property pattern:

if (_data.Item is {} item)
{ 
    // use item
}

Null propagation.

var result = _data.Item?.UseItem()

or in a method

var result = UseItem(_data.Item?.Value ?? "some default value")

This pattern, where myVariable may be located outside of the method

if (myVariable == null)
{
    myVariable = GetSomeFallbackValue();
}
return myVariable;

may be shorten as

return myVariable ?? (myVariable = GetSomeFallbackValue());

and the same with C# 8.0 new syntax

return myVariable ??= GetSomeFallbackValue();

The pattern is often used for lazy initialization in Property getter, and it's suitable for code written in expression form.

private MyClass myBackingField;

public MyClass MyProperty
{
    get => myBackingField ??= new MyClass();
    set => myBackingField = value;
}

The value for backing field will be instantiated on first call of the Property getter. Thus, the value of the MyProperty will never be null.

3 operations at once:

  • check for null
  • conditionally assign fall back value
  • and return (or use) the result
Related