.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

Reader Comments:

Thu, Sep 15, 2011 Peter Vogel Canada

Bob: Good point! To stay consistent with my introduction, which focused on databases, I shouldn't have shifted to using Nothing in my VB sample code. Smells like a follow up tip to me...

Wed, Sep 14, 2011 Bob Iowa

Just a remider that in VB missing database values are returned as DBNull.Value, not Nothing. The statement If(dataReader("SomeColumn"), "DefaultValue") will never return the second value.

Fri, Sep 9, 2011 Gerhard Weiss

Nice little tip. :)

Add Your Comments Now:

Your Name:(optional)
Your Email:(optional)
Your Location:(optional)
Please type the letters/numbers you see above

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.