Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does LastName not show in C# string concat operator below [closed]

Tags:

c#

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"
like image 485
Peter Kellner Avatar asked Jan 30 '26 02:01

Peter Kellner


1 Answers

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.

like image 89
Jon Skeet Avatar answered Jan 31 '26 21:01

Jon Skeet



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!