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 2.0.0 Released
Tweetz 2.0 Beta
VSColorOutput 2.7 - Time Stamps
Fixed Focal-Length Eyeglasses, a Programmer's Best Friend
How to Choose the Right VPN Service
Two Handy Command Line Scripts
Tweetz 1.3.2
More... (1088)