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

Quick Tip - Clear ReSharper's Cache to Fix False Errors
Quick Tip - Refined GitHub
Vertical Layout for HTML Tables
Visual Studio 2017 Installer Quick Tip
VSColorOutput for VS 2017 Released
Quick ReSharper tip for inline templates
NoSQL vs. NewSQL: What's the Difference?
More... (1077)

Donate with PayPal