My coworker is new to C# and didn't know about the coalesce operator. So, I saw him write a line of code like this:
string foo = "" + str;
The idea being that if str is null, this expression would return an empty string. Of course, that could be rewritten as this:
string foo = str ?? "";
And I feel that would be more readable. But is it really that big a deal? Are the readability benefits enough to suggest going back and making those lines look like the second? Or is this one of those things that I should learn to let go (provided that my coworker is educated on the best way to do this in the future)?
EDIT: Just a note, I appreciate the efficiency comments, but this isn't really being used in any situations where that performance would be critical. So while that info is interesting, it's not necessarily what I feel is important.
IMO, it is much better to clearly define such logic i.e. don't use string concatenation to avoid null string and use conditional statement or ?? operator.
Regarding other comments:
there is also a performance benefit to using the null-coalescing operator, since no concatenation need take place (and, therefore, no extra string instance is being created unnecessarily)
Not true. C# compiler compiles "" + string2 to the 100% same code as string1 ?? "". Moreover C# compiler translates + operator to call to string.Concat method which in turn checks arguments with string.IsNullOrEmpty function and doesn't allocate a new string in this case.
Also I would recommend the use of String.Empty over "" as it is a constant and does not require the creation of a new String
.NET framework supports string interning so "" and string.Empty point to the same memory region
I don't think one is any more readable than the other personally. I prefer this:
string foo = str ?? "";
simply because I really like the ?? operator.
If you are a brand newbie, I think that this would be a little easier to understand:
string foo = str == null ? "" : str;
or
string foo = "";
if (str != null) foo = str;
However, you kinda need to ask youself, "How simple do you really want to get?"
While I prefer the second line from the technical perspective, the first line is actually more readable to me...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With