Explain why LastName in below example does not show in C# string concat

I've got code like the following where adding the ?? operator causes last name to disappear. I don't get it. I thought it would be just last name

var first = "Joe";
var last = "Smith"
var str1 = first + last; // gives "JoeSmith"
var str2 = first ?? "" + last // gives "Joe"
Jon Skeet

It's a matter of precedence. + binds more tightly than ??, so your code is effectively:

var str2 = first ?? ("" + last)

It sounds like you probably meant:

var str2 = (first ?? "") + last)

But there's no point, given that string concatenation with null is equivalent to string concatenation with an empty string - so just use first + last as you already have with str1.


See more on this question at Stackoverflow