Matt Casto's .NET Journal RSS 2.0
 Thursday, May 24, 2007
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:

Thursday, May 24, 2007 11:57:00 AM (Eastern Standard Time, UTC-05:00)  #    Comments [6] -
c#
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2009
Matt Casto
Sign In
All Content © 2009, Matt Casto
Theme based on DasBlog theme 'Business' created by Christoph De Baene (delarou)