Some of the things I read in R. Aaron Zupancic's blog post
New Operator in C# 2.0: ?? caught me off guard. I swear I'd read through several articles listing changes and additions in .NET 2.0 and C# 2.0, including MSDN, but never ran across the
?? operator. I even checked the
C# Operators documentation and didn't see
?? Operator until the second pass, because it's grouped in the assignment category. I expected it to be grouped in the conditional category with
?:, but now I'm wondering why ?: isn't considered an assignment operator?
While the null coalescing operator is cool and looks nice in code, I'm not sure how much I'll use it. Most of my code where I'm checking whether a variable is null throws an exception or takes some other action instead of using another value in place of the null variable.
The most interesting thing that I noticed was the following comment from
Owen Blacker:
It's even cooler than that. The null coalescing operator does type forcing, too.
Imaging you have this:
public int? GetUserID() { ... }
int userID = GetUserID() ?? -1;
The ?? operator not only provides an alternative value if GetUserID returns null, but it also does type conversion, from the int? result of GetUserID to a non-nullable Int32, if it returns a non-null result.
I was really thrown off by the
int? part of the example code in the comment above. I eventually found that it's the same thing as
NullableType. That's really nice syntax to replace using a nullable value type. Before I knew what it was, I immediately assumed that it was something like a nullable type. The question mark following the value type suggests that you're not sure that the returned value will be integer or not. I will
definitely get some mileage out of this information. Finally, a way to represent a value from a SQL bit column in code.
I'm not sure why I forgot about
Nullable Types. I do recall reading about them in the feature list for a .NET 2.0 beta, but I don't remember seeing anything about them in any "what's new" articles. Maybe I just missed it.
Back to the operator, I think the next example reads a lot cleaner than the following one which uses the NullableType's GetValueOrDefault() method. Of course, its probably better to use that method so you aren't hard coding a value type's default value in code (not that it would change).
Using the
?? operator:
int? x = null;
int y = x ?? 0;
Using the GetValueOrDefault() method:
int? x = null;
int y = x.GetValueOrDefault();
It's interesting that the null coaelscing operator post is making rounds now, almost exactly a year after it's original posting.
Labels: c#