:::: MENU ::::

Monday, September 29, 2008

I was looking through some code the other day and ran across something that looked remotely familiar.  It was the null coalescing (??) operator.  I had read about this operator, but never used it.  It was introduced with the .NET 2.0 Framework.

The null coalescing operator basically checks to see if a value is null and if so returns an alternate value.  Below is a simple example.

C# Code Listing

using System;
 
namespace CoalesceTst
{
    class Program
    {
        static void Main(string[] args)
        {
            string userName = "GabrielGray";
            string userName2 = null;
 
            string name = userName ?? "<no name>";
            string name2 = userName2 ?? "<no name>";
 
            Console.WriteLine(name);
            Console.WriteLine(name2);
        }
    }
}