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}");
}
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.