C# null-coalescing operator ??

  • Home
  • Blog
  • C# null-coalescing operator ??

C# language provides many features and null-coalescing operator(??) is one of them. It’s a great operator to check whether object is null and if it is null then it will provide a default value. I have seen most of the people are not using while it’s a great feature. So I decided to write a blog about this. You can find more information about null-coalescing operator from the below link.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

In below example we are checking nullable integer value whether its having value or not. First we are going to simple check with if else and then we are going to check same with null-coalescing operator.

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
            Console.WriteLine(Number);
            Number = 1;
            Console.WriteLine(Number);
        }

        public static int? _number;

        public static int? Number {
            get {
                if (_number.HasValue) {
                    return _number;
                }
                else
                    return 0;
            }
            set {
                _number = value;
            }
        }
    }
}

Here in the number property I have used the if-else loop to check whether number has value or not. We can simply use null-coalescing operator to check whether it has value not like it.

using System;
namespace ConsoleApplication3
{
    class Program
    {
        static void Main() {
            Console.WriteLine(Number);
            Number = 1;
            Console.WriteLine(Number);
        }

        public static int? _number;

        public static int? Number {
            get {
                return _number ?? 0;
            }
            set {
                _number = value;
            }
        }
    }
}

Out put of both code will be same like following.

That’s it. Hope you like. Stay tuned more..