Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 271
avo Avatar asked Jul 10 '20 23:07

avo


Video Answer


2 Answers

Also you can use empty property pattern:

if (_data.Item is {} item)
{ 
    // use item
}
like image 150
Guru Stron Avatar answered Oct 13 '22 12:10

Guru Stron


Null propagation.

var result = _data.Item?.UseItem()

or in a method

var result = UseItem(_data.Item?.Value ?? "some default value")
like image 38
Jeff Avatar answered Oct 13 '22 13:10

Jeff