Search code examples
c#string-concatenation

String concatenation with null-coalescing operator


I was trying to build a string like the following and I noticed that it gets cut off after using the ?? operator, regardless of whether the previous value is null.

"Some Text" + System.Environment.NewLine +
varOne.ToString() ?? string.Empty + System.Environment.NewLine +
varTwo.ToString()...

All that the string contains (regardless of the values) is up to varOne (Some Text + newline + varOne) unless I remove the ?? operator. After looking around a bit I see that this is not the preferred way of doing this and that I should probably use a stringbuilder instead but I was just curious as to why this happens?


Solution

  • Have a look at ?? Operator (C# Reference)

    The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand.

    This implies, stuff after ?? is only assigned, if stuff before it is null.

    So

            string sNull = null;
            string s = sNull ?? "TADA";
    

    s would be TADA

    and

            string sNull = null;
            string s = sNull ?? "TADA";
            string sNormal = s ?? "NOT TADA";
    

    sNormal would also be TADA