Assignment operation that does nothing if variable is null?

c# null conditional operator if statement
c# assign to variable if not null
c# check if object property is null
null coalescing operator
c# set field if null
c# join null check with assignment
check if (model is null c#)
c# null conditional operator linq

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

if you're concerned about doing this all in a single statement, you're out of luck - C# doesn't have this functionality at the linguistic level and doesn't support operator declaration (as does F#) or overloading of the assignment operator (as does C++). There are, however, a couple of options, if none quite as elegant as you requested.

The if statement, as you mentioned, though it can be written as a single line

if(a == null) a = b;

A helper method which uses a ref parameter

public void AssignIfNull<T>(ref T target, T value)
{
    if(target == null) target = value;
}

// ...

AssignIfNull(ref a, b);

Note the above will not work with a Property, since they cannot be passed as a ref parameter.

EDIT: While the above is similar to Interlocked.CompareExchange, such an alternative returns the original value of the first parameter, so it may prove more of a gotcha than implementing the above method.

Or you could carefully rewrite your initial statement to use a null-coalescing (??) operator in the initial assignment.

?? and ??= operators, The null-coalescing operator ?? returns the value of its left-hand The ?? operator doesn't evaluate its right-hand operand if the The left-hand operand of the ??= operator must be a variable, a property, or an indexer element. In particular, beginning with C# 8.0, you can use the null-coalescing  You can also assign the value created by a statement to a variable, as in the following example: PowerShell. $a = if ($b -lt 0) { 0 } else { $b } This example assigns zero to the $a variable if the value of $b is less than zero. It assigns the value of $b to $a if the value of $b is not less than zero.

As you said, an if statement is what you need. There is no conditional operator that doesn't assign when null. An if is most suitable in this case (not everything has to be a oneliner).

The best options:

if(a == null)
{
    a = b;
}

Or:

a = a ?? b;

In fact, I believe that the latter is optimized away as a simple if statement.

Assigning a to itself isn't bad. With object references, it is just an assignment of the memory address. For value types, this is just a little chunk of data.

If a is actually a property setter, check inside the setter the value has changes:

private string a;

public string A
{
    get
    {
        return a;
    }
    set
    {
        if (value != a)
        {
            a = value;
        }
    }
}

Using the New Null Conditional Operator in C# 6 |, Suppose people is a variable that represents an IList<Person>. If people is null​, thisName is assigned the value null. operator with the traditional member access operator, the resulting expression will return null if the left  The concept of a null keyword is that it gives a variable a neutral, or "null" behaviour. Note that technically the behaviour of null changes between higher and lower-level languages, so to keeps things simple we'll be referring to the concept in object-orientated languages. Python's null Equivalent: None

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

Powershell: check variable for null, ??= null conditional assignment operator, you can easily assign a variable a value, but only if the variable is $null. Here are some examples: #Variable which is  Is there a way to do a java ternary operation without doing an assignment or way to fake the assignment? OK, so when you write a statement like this: (bool1 && bool2) ? voidFunc1() : voidFunc2(); there are two distinct problems with the code: The 2nd and 3rd operands of a conditional expression 1 cannot be calls to void methods. Reference: JLS

Having run into this situation myself, I decided to check my code where I deal with this. I tend to have two solutions, both involving the null coalescing operator.

Case 1: Initialization. Using your values from above, this becomes:

object a = null ?? something;

Obviously, I wouldn't write that line of code (resharper would complain if nothing else). But it is the essence of what is happening. If I have the two (or more) values available when I create a, then I write it like this.

Case 2: Never set a, but use ?? when a is used. In this case, the code would be:

MethodTakingA(a ?? b);

If there are multiple method calls or other places where I'd need to use ??, then this is a bad idea.

There is a third case where I do the exact assignment you are avoiding. That is when one of the parameters to my method might be null, and I have a default value to use in that case (as opposed to throwing an ArgumentNullException). Here's an example:

public void Foo(string str)
{
  str = str ?? String.Empty;
  //Use str as needed below without fear that it might be null.
}

I'd like a better answer for this case, but I'm certainly not writing code where micro-optimizing that assignment is worthwhile, and the theoretical answer of

string localStr = str ?? String.Empty;

Is just adding a new variable to add one. It otherwise serves me no purpose, so I keep my self-assignment and live with it.

Nothing vs Empty vs Null with VBScript, Why does VBScript have Null , Nothing and Empty , and what are the differences between them? variable's value before the first assignment is undefined, or Empty . If you need to detect whether a variable actually is an empty variant Since the equality operator on objects checks for equality on the  Use the Nullable<T>.GetValueOrDefault() method if the value to be used when a nullable type value is null should be the default value of the underlying value type. Beginning with C# 7.0, you can use a throw expression as the right-hand operand of the ?? operator to make the argument-checking code more concise:

As a single statement,

var result = ((a == null) ? (a = b) : null);

The value of result can then be discarded. Having a and b as object properties, and adding a Console.WriteLine() on the setting for a will show that it is only assigned to when it was previously null.

The only thing that stops it being perfectly clean is that a throwaway variable result is created; hopefully it's still clean enough.


Addendum - I've just realised you can also use:

var result = a ?? (a = b);

as an even shorter version of the above. Again, a = b is only evaluated if a is null.

The Definitive Guide to SUSE Linux Enterprise Server, ${parameter=value} Assigns the value to the parameter if the parameter does not exist. This operator does nothing if the parameter exists but doesn't have a value. In all of these examples, something happens to the $BLAH variable. You'll  Given that, there's a general notion that expressions which might usefully 'return' a value may as well do so. Assignment chaining can be slightly "interesting" in C, and even more interesting in C++, if all the variables in question do not have precisely the same type. Such usages are probably best avoided.

Using "${a:-b}" for variable assignment in scripts, This technique allows for a variable to be assigned a value if another variable is either empty or is undefined. NOTE: This "other variable" can be the same or  Assigning Nothing to a nullable variable sets the value to null. For more information and examples, see Nullable Value Types. If a variable is of a value type that is not nullable, assigning Nothing to it sets it to the default value for its declared type. If that type contains variable members, they are all set to their default values.

VBA: null, nothing and more (or less), An object can be tested for nothingness with the is nothing construct: if obj is nothing empty. The value of a (variant) variable is empty if it has not yet been assigned a value. variable. Any operation that involves null values evaluates to null. At run time, the as keyword causes the downcast assignment statement to assign null if the downcast isn't valid. This is keyword is often used to safely test whether the as keyword will work. Code example for the as keyword In the following code example, the DerivedClass class extends the BaseClass class.

How to Determine If Variable is Undefined or NULL in JavaScript, In JavaScript if a variable has been declared, but has not been assigned a value, To check if a variable is undefined or null you can use the equality operator  'returns False - is an Empty variable, not a Null variable - no beginning value has been assigned to a Variant variable: MsgBox IsNull(var1) 'Empty indicates a Variant variable for which you do not explicity specify an initial value, which by default gets initialized in VBA to a value that is represented as both a zero and a zero-length string.

Comments
  • So I assume a = a ?? b; is out?
  • @JoelRondeau Appears so - OP doesn't want a being assigned back to itself.
  • Then you have to use the if to avoid the assignment. I don't see any other option. Anyway, doing a = a shouldn't be a problem at all, unless the setter has some huge logic.
  • You says things like a = a ?? b end up performing a = a if a is not null, but you don't explain why this is a problem.
  • Do you have a reason for not wanting a = a? Is that somehow detrimental to your application?
  • Does a = a still trigger the object's set method? I don't really want that triggered.
  • Oh, sorry, my bad. :)
  • Why the downvote? this does exactly what the OP asked
  • I didn't downvote, but this is just an obscure way to do an if. In fact the ? does that.
  • The difference is that ? returns an expression that has to be assigned to some variable. the only way to get rid of that variable is to make it return lambdas and execute it like javascript self executing functions
  • I didn't downvote, it's an interesting hack but I think the code ends up being somewhat cryptic.
  • I definitely will just do an if, but I had to post the answer for completeness