I've got code like the following where adding the ?? operator causes last to disappear.
Expected Result: was that if first was null then first would be replaced by "" and that "" would be concatinated with last giving just last as the result.
Actual Result: What happened was the result I got was just first.
var first = "Joe";
var last = "Smith"
var str1 = first + last; // gives "JoeSmith"
var str2 = first ?? "" + last // gives "Joe"
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