5,317,598 members and growing! (28,290 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate

The Null Coalescing Operator (??)

By TheCodeKing

One of the most useful yet little-known features to come out of C# 2.0
C# 2.0, C# 3.0, C#, Windows, .NET, .NET 3.0, .NET 2.0VS2005, Visual Studio, Dev

Posted: 28 Sep 2007
Updated: 28 Sep 2007
Views: 10,825
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
25 votes for this Article.
Popularity: 6.37 Rating: 4.56 out of 5
0 votes, 0.0%
1
1 vote, 4.0%
2
1 vote, 4.0%
3
8 votes, 32.0%
4
15 votes, 60.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

I'm constantly surprised by the number of developers who aren't aware of this handy piece of syntax. It's my favourite thing to come out of C# 2.0 and no developer should be without it.

Like the conditional (?:) operator's big brother... introducing for your coding pleasure...

The Null Coalescing Operator (??)

The null-coalescing-operator is a brilliant new terse operator that provides syntax for beautifully concise if statements. Essentially it returns the left-hand-side of the ?? operator, unless null, in which case it executes and returns the right-hand-side of the operator. This may be a statement or a variable reference. Lets jump straight to some examples.
    // used inline outputs the value foo or if null returns Undefined

    Console.WriteLine("The value of foo is " + (foo ?? "Undefined") + ".");
    
    Input:  foo = "24";
    Output: The value of foo is 24.
    
    Input:  foo = null;
    Output: The value of foo is Undefined.
The operator is right-associative meaning statements can be chained together; thus returning the first non-null instance.
    // assigns foo to the first non-null instance, else returns Undefined

    string foo = foo1 ?? foo2 ?? foo3 ?? foo4 ?? "Undefined";
    
    Console.WriteLine("The value of foo is " + foo + ".");

    Input:  foo1 = null;
            foo2 = null;
            foo3 = null;
            foo4 = null;
    Output: The value of foo is Undefined.
    
    Input:  foo1 = null;
            foo2 = "foo2";
            foo3 = null;
            foo4 = "foo4";
    Output: The value of foo is foo2.
Handling null ViewState references.
    // try to assign ViewState value as an int, else if null assign 123

    int foo = (int?)ViewState["foo"] ?? 123;
    
    Response.Write("The value of foo is " + foo + ".");
    
    Input:  ViewState["foo"]=1;
    Ouput:  The value of foo is 1.  
    
    Input:  ViewState["foo"]=null;
    Ouput:  The value of foo is 123.  
And my personal favorite, on demand field instantiation.
    private IList<string> foo;

    public IList<string> Foo
    {
        get
        {
            return foo ?? (foo = new List<string>());
        }
    }
Here's an interesting example devired from an idea in the discussions below. It shows how an operator override can be used within an object's definition to enable shorthand syntax for double-null checking. The scenario is checking a object property for null using a null-coalescing-operator, but also defaulting when null-object-reference occurs; which would normally cause a runtime exception. (Note I don't recommend actually using this approach, I just thought it made an interesting example).
   public class Address
   {
       private static Address Empty = new Address();
       public string StreetName = null;

       public static Address operator +(Address address)
       {
          return address ?? Empty
       }
    }
  
    Console.WriteLine("The street name is "+ (+address).StreetName ?? "n/a" + ".");
  
    Input:  address = new Address();
    Ouput:  The street name is n/a.  
    
    Input:  address = new Address();
            address.StreetName = "Regent St";
    Ouput:  The street name is Regent St.    
    
    Input:  address = null;
    Ouput:  The street name is n/a.   
  

The Rules

To use the null-coalescing-operator there are some compile-time ground rules.

  • The left-hand-side must evaluate to a reference or nullable type.
  • All evaluated statements must be of matching type, unless they can be implicitly converted.

Summary

As you can see from the examples above, this little gem is very powerful and the possibilities are endless. Of course the benefits are purely syntactical, but it helps keep the code clean and easier to follow. I hope you enjoy it as much as I do.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

TheCodeKing


Mike Carlisle - Senior software engineer with over 10 years experience in a wide range of technologies.
Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular C# articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 24 of 24 (Total in Forum: 24) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralAn alternate viewmemberBig Al 077:38 1 Oct '07  
GeneralRe: An alternate viewmemberTheCodeKing9:18 1 Oct '07  
GeneralRe: An alternate viewmemberHal Angseesing10:06 1 Oct '07  
GeneralRe: An alternate viewmemberBig Al 0715:47 1 Oct '07  
GeneralRe: An alternate viewmemberkschulz13:08 1 Oct '07  
GeneralRe: An alternate viewmemberMatware17:24 1 Oct '07  
GeneralRe: An alternate viewmembergreenblob6:12 3 Oct '07  
GeneralRe: An alternate viewmemberreinux20:06 18 Oct '07  
GeneralRe: An alternate viewsupporterpeterchen11:25 5 Jan '08  
GeneralThis thing existed?!memberreinux10:12 29 Sep '07  
GeneralThanksmembergajatko1:19 29 Sep '07  
GeneralA handy operatormemberlogan133712:50 28 Sep '07  
GeneralRe: A handy operatormemberDaniel Grunwald13:30 28 Sep '07  
GeneralRe: A handy operatormemberlogan133714:01 28 Sep '07  
GeneralRe: A handy operatormemberDaniel Grunwald1:18 29 Sep '07  
GeneralRe: A handy operatormemberTheCodeKing14:09 28 Sep '07  
GeneralRe: A handy operator [modified]memberTheCodeKing14:24 28 Sep '07  
GeneralRe: A handy operatormemberTheCodeKing13:42 28 Sep '07  
GeneralRe: A handy operatormemberTheCodeKing13:44 28 Sep '07  
GeneralRe: A handy operatormemberlogan133713:56 28 Sep '07  
GeneralRe: A handy operatormemberTheCodeKing14:02 28 Sep '07  
GeneralRe: A handy operatormemberJoshuaMcKinney21:39 6 Oct '07  
GeneralRe: A handy operatormemberlogan13378:42 8 Oct '07  
GeneralRe: A handy operatormemberTheCodeKing9:17 8 Oct '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 28 Sep 2007
Editor:
Copyright 2007 by TheCodeKing
Everything else Copyright © CodeProject, 1999-2008
Web17 | Advertise on the Code Project