Home > Mobile >  assigned null value in Null-coalescing assignmen C#
assigned null value in Null-coalescing assignmen C#

Time:12-10

If the phrase ?? = in C # is for assigning null then why is the value assigned in this example?

IList<string> list = new List<string>() {"cat" , "book" };

(list ??= new List<string>()).Add("test");

foreach (var item in list)
{
    Console.WriteLine($"list ??= {item}");
}

CodePudding user response:

You are misunderstanding the operator. It isn't for assigning null. Rather, it does a check for null and, if the checked variable is null, it assigns the righthand value.

To better visualize what is happening, it helps to write out the longhand version of the null coalescing operator:

(list = list ?? new List<string>()).Add("test");

In the above, it checks to see if list is not null and if it is not, it assigns the list variable to the current list variable, and finally, then adds "Test" to the collection.

Since your list has been initialized above, there's no need to assign a new list.

CodePudding user response:

As Microsoft Docs says:

the null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

Your list is not null, that's why ??= does not assign new List.

  • Related