Geeks With Blogs
Blog Moved to Blog Moved to
When I was studying for the 70-536 exam and now studying for the 70-528 exam, I've done quite a bit of studying of the new language features.  One of them that caught my eye was the null-coalescing operator.  If you look at section 19.5 of the C# 2.0 Specification document, it covers this in detail with several scenarios.
When I first saw this feature, I was a little bit skeptical.  I like functions to make my life easier, but they should be easy to understand and not obfuscate what the ultimate result is.
Let's look at the following statement:
string myValue = null;
Console.WriteLine(myValue ?? "Nothing at all");
The output from this would be:
"Nothing at all"
So, what does this do for us?  Let's compare it to the previous way in C#.
string myValue = null;
Console.WriteLine(myValue == null ? "Nothing at all" : myValue);
As you can see, there's not too much difference here except that it broke down the conditional operator.
Now, let's look at value types and how this can be used.  Take for example, this scenario:
int? myNum = null;
int answer = myNum ?? 0;
The result of the answer would be 12 since myNum was null.  As you can imagine, you can only use this on the Nullable value types by either using the ? or the Nullable<T> structure.
So, in conclusion, it's another tool to add to the bag when dealing with types that can be null.  Even though my favorite language is C++ and probably will be, I love working with C# and some of these improvements make me love it even more.
Posted on Wednesday, July 5, 2006 8:15 PM Microsoft , .NET , C# | Back to top

Comments on this post: C# Null-Coalescing Operator

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Matthew Podwysocki | Powered by: