Mike-Ward.Net

C# 2.0 ?? Operator

I’m surprised how many of my colleagues don’t know about this little operator. Termed the null coalescing operator, it returns the left hand operand if not null, else the right hand operand. It makes for handy shortcuts in code and I think actually improves the readability when used judiciously. Here’s an example:

Console.WriteLine(name ?? "Unspecified");  

Seems self-explanatory and it’s fewer keystrokes to boot. It’s also nice for lazy evaluation type statements:

public User TheUser
{
  get { return theUser ?? (theUser = new User()); }
}

Phil Haack postulates that this operator is thread safe based on an examination of IL. Don’t know if that is true since I’m no IL expert either but since the left hand side is evaluated only once, there’s a strong indication that it is.

There’s also a good article about the null coalescing operator at the Code Project.

Finally, you can use ?? with value types in limited situations as described here.

← newer older →
.Net, Technology, Life, Whatever

Recent Posts

Tweetz 1.3.2
Tweetz 1.3 Release
Mithril Rising
Tweetz Release 1.2.4 - Screen Off Detection
Tweetz Desktop Support for 280 Characters
Quick Tip - Clear ReSharper's Cache to Fix False Errors
Quick Tip - Refined GitHub
More... (1082)

Donate