Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment operation that does nothing if variable is null?

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
like image 672
LCIII Avatar asked Dec 04 '14 15:12

LCIII


2 Answers

Updated

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

Original Answer

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; }

like image 185
Carlos Muñoz Avatar answered Sep 19 '22 04:09

Carlos Muñoz


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;
like image 38
nzrytmn Avatar answered Sep 19 '22 04:09

nzrytmn