Learning null-coalescing operator

I am pretty sure that most of the guys has never knew this operator and its also very rarely used. Since C# provides this and this is very useful and handy at certain times.

The short from of null-coalescing operator is ??.

It actually takes two operands.  So it returns the left hand operand if it is not null else returns right operand. So this is very useful while initializing any variable. let’s see a example

string name = null;
string otherName = "Brij";
string userName = name ?? otherName;

As you can see, here is name is null then userName is assigned to otherName. and it will print Brij.

This is also useful in scenario like if the data/message/string is null then if you want to show some default message. Say I have array of bookNames and I have to find to 4th index name but say 4th index doesn’t exist at all then we’ll show a custom message like index does not exist like

 static void Main(string[] args)
            string bookName = GetBookName(4) ?? "No book found at this index";

        private static string GetBookName(int index)
            String[] arrayOfBooks = new string[3] { "WorkFlow Foundation", "CLR via C#",
 "ASP.NET Professional" };
            if (arrayOfBooks.Length > index)
                return arrayOfBooks[index];
                return null;

Above example is self explanatory and it show the output No book found at this index. As no book is available at 4th index and GetBookName returns null.

One very good thing, It is not only works with Reference types but also works with Nullable types( I discussed Nullable types in earlier post) as well. It cannot work with Value types because value type cannot have null.

Also this operator works very efficiently with expressions as well. Like

 static void Main(string[] args)
       Func<string> fun = () => GetName() ?? "No Name";


private static string GetName()
     return null;

Hope this will help you guys.




4 thoughts on “Learning null-coalescing operator

  1. Hello Mr. Brij.
    First of all, my warm wishes to you leading you ahead with stepping in a new days, new events and new year.
    I went through your article regarding State Management and it’s techniques on one of the most preferred e-tutorial sites http://www.codeproject.com. And I found it’s really helpful to me. I didn’t go through end of this article and got excited to know the author of the article and found your little description. Mr. Brij, not only me even we all Indians feel proud of you exploring the India in world. And yes, I am not much proficient in .NET development but thirsty to do some like you.
    I also enjoyed your blogs and relearned about nullity and a new feature “Unobtrusive validation ” feature of ASP.NET 4.5.
    Wish you all the best for great career and hope we will enjoy more and more articles in future too.

    • Thanks a lot for such a nice comments. Wish you also a very happy new year and a brilliant future ahead.

      Glad to know that you find my articles useful. Yiu can also subscribe my blog to get a notification when a new blog post is posted.

      Thanks again!!

  2. Pingback: Using Null Conditional operators | Code Wala

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s