Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 891
aw04 Avatar asked Feb 01 '26 21:02

aw04


1 Answers

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

like image 104
Adriaan Stander Avatar answered Feb 03 '26 11:02

Adriaan Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!