.NET, C#, Programming Tutorial

Null-coalescing operator – ?? Operator in C#

The ?? operator is called the null-coalescing operator and is used to define a default value for nullable value types or reference types. It returns the left-hand operand if the operand is not null; otherwise it returns the right operand. (MSDN)

Let’s take a sample to see how it work?

using System;

namespace Test
{
    class Program
    {
        static void Main()
        {
            string myString = null;

            if(myString == null)
            {
                Console.WriteLine("NULL");
            }
            else
            {
                Console.WriteLine(myString);
            }

            // We also write like this
            Console.WriteLine(myString ?? "NULL");

            Console.ReadKey();

        }
    }
}

The output is:
NULL
NULL

Advertisements

2 thoughts on “Null-coalescing operator – ?? Operator in C#”

  1. I do consider all of the concepts you have presented
    to your post. They’re really convincing and can certainly work. Still, the posts are too short for novices. May just you please extend them a little from subsequent time? Thanks for the post.

    1. Thanks for your interesting in my post.
      My purpose is providing to all you the simplest way to know how to something work and make it easy to understand ASAP. But I’ll regard your helpful suggestion in next posts.
      Now, if you want some extensions, I can help you by giving a nice link from MSDN that has full description about ?? operator.
      Here is link: http://msdn.microsoft.com/en-us/library/ms173224.aspx
      Nice reading, 🙂

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 )

Google+ photo

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

Connecting to %s