Is there a shorter way to write this in C# 8?

163 Views Asked by At
if (value2 != null)
{
    value1 = value2;
}
                

? and ?? operators don't seem to be useful here. I thought of using the ternary operator.

value1 = (value2 != null) ? value2 : value1;

Doesn't seem good. Is there a shorter way?

1

There are 1 best solutions below

9
On

It seems that this is the closest:

value1 = value2 ?? value1;

I feel like your original if is more readable.

The ?? operator is most useful if you use it within an expression. Like this:

var x = (value2 ?? value1) * System.Math.Pi();