I was writing some code today for a utility method to format names. You know, one of those functions that you find yourself writing even thought you've probably done it lots of times in the past, but you can't find the previous versions.
I got to the part where it returns different values if other values are available, and realized something as I wrote the following code.
if (!string.IsNullOrEmpty(lastName))
return lastName;
else if (!string.IsNullOrEmpty(firstName))
return firstName;
else if (!string.IsNullOrEmpty(middleName))
return middleName;
else
return string.Empty;
I realized that I could probably condense that into one line if I could chain together the variables with
null coalescing operators. "What the hell," I thought, "I'll give it try and see if it compiles."
return lastName ?? firstName ?? middleName ?? string.Empty;
Sure enough, it compiles. And it works!
It's always a nice feeling to write beautiful code.
Labels: c#