Making decisions easier for null values with the ?? (null coalescing) operator

by Dominic Zukiewicz 1. July 2008 15:50

When catering for null values, I use the ternary operator ?, which is used to do an inline IF statement. For example:

public void CheckText(string text)
{
    if(String.IsNullOrEmpty(text))
    {
        throw new ArgumentException("Parameter is " + (text==null ? "null." : "empty."));
    }
    
    //Other code here
}

This would allow you to cater for 2 exception cases:

  1. When the parameter is null, the exception message states "Parameter is null.";
  2. When the parameter is "", the exception message states "Parameter is empty.";

Since testing for null is a fairly common operation, and also catering for the possibility of a null, there is an operator called the null coalescing operator. The operator is used to check a value for null, and return an alternative value if the result is null

Before:

string text = ReadFromDB();
 
if(text == null)
    Console.WriteLine("(null)");
else
    Console.WriteLine(text);

After:

string text = ReadFromDB();
 
Console.WriteLine( text ?? "(null)" );

So, the way it works is it checks the first variable. If it is not null it returns the first variable, otherwise it returns the second. It is a shorthand method of this made up method:

public static object GetObject(object o, object _default)
{
     if( o == null )
          return _default;
     else
        return o;
 
    //Or return (o==null?_default:o);
}

The main use of this would be for outputting data to a table, or to a stream - but it looks like something I will definitely use in the future, instead of my long winded ternary operators ?

Tags:

Framework

Powered by BlogEngine.NET 1.5.0.7
Theme by Interakting

Interakting

A full service digital agency offering online strategy, design and usability, systems integration and online marketing services that deliver real business benefits and ensure your online objectives are met.

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar