I want to conditionally assign a value to a variable if that variable is already null
. Furthermore, if that variable is not already null
I want nothing to occur and I want to be able to do all with a single operator.
object a = null;
object b = new Something();
// this is essentially what I want but done with an operator:
if(a == null)
{
a = b;
}
// this is all I feel I have to work with,
a = a || b;
a = a ?? b;
a = a == null ? b : a;
// the above methods all end up performing a = a if a is not null
Since C# 8 this is possible with the Null-coalescing assignment operator
a ??= b;
This will only assign b
to a
if a
is null
Although the syntax is verbose
(a is null?()=>a=b:(Action)(()=>{}))();
Let's break it apart
( // Expression starts here
a is null // If a == null...
? () => a = b // return lambda that assigns a = b
: (Action) ( // Else return next lambda casted as Action
() => {} // Empty lambda that does nothing
) // End cast
) // Expression ends here
(); // Execute it!
Anyway I would just use the one liner if if(a is null) { a = b; }
I think the new feature that came with C# 8.0, make this pretty easy .There is a new ??= operators that chek the variable and if it is null than set the value , if not than nothing.
if (variable is null)
{
variable = expression;
}
is simply doing as
variable ??= expression;
in your case it is :
a ??= b;
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