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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With