??= In C#

C# has had the null coalescing operator ?? For a while now. It lets you condense

if (x = null)
{
y = x;
}
else
{
y = otherThing;
}

into

y = x ?? otherThing;

It’s a great tool for both condensing code and improving readability.

I found out recently though that C# 8.0 expanded on that idea. There is a common design pattern of caching a computed value in a variable so you only have to compute it once.

private int? _Example = null;
Public int? Example
{
get
{
if (_Example == null)
{
_Example = ComputeExample();
}
return _Example;
}
}

This isn’t that bad. It works. But it’s tedious to write (especially on mobile like I am now for this post). Enter the null coalescing assignment operator.

private int? _Example = null;
Public int? Example
{
get
{
return _Example ??= ComputeExample();
}
}

I love it!

Leave a Reply

Your email address will not be published. Required fields are marked *