Every so often something comes across one's desk that results in a “hey! what's that!?” moment. Now I'd like to believe that I have acquired a deep level of comfort and familiarity with the syntax of my favorite development language (C#). Today, however, I had one of those moments. I saw a line of code that resembled:
Console.WriteLine(userName ?? "User name not specified");
Note the ?? operator. It took me a bit to find information about it, I really had to do some digging - it wasn't coming up on the msdn sites...I wonder if the search engines just didn't like the question marks. Whispering from the recesses of my mind I seemed to recall having seen it, but all memory of its usefulness had vanished...I had to relearn it.
Anyway, this operator (termed a null coalescing operator) is new in C# 2.0...and it's pretty slick. The null coalescing operator provides inherent null-checking capabilities. The result of the expression is based on whether the first operand is null. If the first operand is not null, it is the result of the expression, otherwise, the result falls to the second operand. In other words, return the first value if not null, otherwise the second.
In effect, the previous line could be written thus:
Console.WriteLine( null != userName ? userName : "User name not specified");
That's pretty awesome - especially since in general I'm a fan of the ternary, conditional operator (?:), I think I can really fall in love with this new capability. I suppose the null coalescing operator (??) is just syntactic sugar, but I like it nonetheless.
Let's suppose you had a function named 'getCustomer' that accepts an id that is used to retrieve a customer object from some underlying store (such as a database, collection, file, etc). If the customer exists, it is returned. However, if it doesn't exist, a value of null is returned. In this particular instance you might have an operation that indicates that if the customer doesn't exist to create a new one:
Customer cust = getCustomer(id);if ( null == cust ) cust = new Customer();
You could effectively rewrite the previous lines as
Customer cust = getCustomer(id) ?? new Customer();
Note, you would NOT want to do the following for reasons which are self evident.
Customer cust = ( null == getCustomer(id) ) ? getCustomer(id) : new Customer();
A couple of links that I did eventually find which are good reads: Fritz Onion's blog and Oliver Sturm's blog.
Ya (re)learn something new everyday.
Remember Me
a@href@title, b, i, strike
Powered by: newtelligence dasBlog 2.0.7226.0
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008R. Aaron Zupancic
E-mail