.NET Tips and Tricks

Blog archive

Generating Default Values for Nulls with Coalescing Operator

Generally speaking, developers hate nulls. While an integral part of relational database theory (where they represent an unknown value), eventually nulls get passed to some variable that won’t accept them and your code blows up. Coalesce operators allow you to check for nulls and return a default value when one is found—and do it in a single line of code.  In Visual Basic, the coalesce operator is If(), in C#, it’s ??.

This example checks to see if a nullable integer value is, in fact, set to null and, if it's not, returns datatypes's minimum value:

Visual Basic version:
  Dim x As Integer?
x = Nothing
Dim y As Integer
y = If(x, Integer.MinValue)
C# version:
  int? x;
x = null;
int y;
y = x ?? int.MinValue;
In some ways, you can think of this as providing a default value when a null value is provided. 

Posted by Peter Vogel on 09/08/2011 at 1:16 PM


comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.