This is something that came up in the comments last week. I was refactoring some code and wound up with the accessor method below that performs multiple null checks while trying to assign a value to _currentUser.
// CurrentUser
private WebUser _currentUser;
public WebUser CurrentUser
{
get
{
if (_currentUser == null) _currentUser = GetWebUserFromSession();
if (_currentUser == null) _currentUser = GetWebUserFromTrackingCookie();
if (_currentUser == null) _currentUser = CreateNewWebUser();
return _currentUser;
}
}
Now this code is pretty clear, but a reader named Brian pointed out in a comment that we could shorten the code a bit by using the Null Coalescing operator “??”. If you haven’t used the Null Coalescing operator yet, check it out. It’s great for data access code where a method may return data or a null value. The basic syntax is illustrated in this block of code from msdn:
// y = x, unless x is null, in which case y = -1. int y = x ?? -1; // Assign i to return value of method, unless // return value is null, in which case assign // default value of int to i. int i = GetNullableInt() ?? default(int);
So, this is really cool, but there’s more. What Brian pointed out was that you can chain the ?? operator to do multiple null checks. So, my block of code above can be rewritten like this:
// CurrentUser
private WebUser _currentUser;
public WebUser CurrentUser
{
get
{
_currentUser = _currentUser ??
GetWebUserFromSession() ??
GetWebUserFromTrackingCookie() ??
CreateNewWebUser();
return _currentUser;
}
}
Note that normally the _currentUser assignment would fit all on one line but due to the width limitation of my blog I broke it up into multiple lines. So, C# Null Coalescing operator chaining. I like it. I’ll be adding it to my toolbox.
Addendum:
Hey, you guys pretty much hated this change to the code. I got no blog comments but I received quite a few emails about this technique and the prevailing opinion seems to be that the original syntax with the multiple if blocks was clearer. In fact, not a single person who emailed me liked the ?? method. So I took another look and I think I agree. The original code does seem a little clearer to me and I don’t really think I was able to make my code any shorter or simpler by using ??. So this may not have been the best example, but I do still think this is a very cool technique for the right situation. As always, I just need to make sure that I’m refactoring because the changes make the code cleaner, not just because they’re clever.