0

Possible Duplicate:
What do two question marks together mean in C#?

What is the usage of ?? in .Net? How it can be used to check while assigning the variables? Could you please write some code snippet to better explain the content ? Is it related with some nullable ?

Community
  • 1
  • 1
mmk_open
  • 1,005
  • 5
  • 18
  • 27
  • 1
    Definitely a dupe. Can't be bothered to search, just like the OP.... – leppie Jun 27 '11 at 11:59
  • 2
    Although it is considered as duplicate by many people, it is still the first search result in Google, so I would close other duplicates instead of this one! – Bistro Feb 14 '12 at 04:14

2 Answers2

2

The operator '??' is called null-coalescing operator, which is used to define a default value for a nullable value types as well as reference types.

It is useful when we need to assign a nullable variable a non-nullable variable. If we do not use it while assigning, we get an error something like

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

To overcome the error, we can do as follows...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GenConsole
{
    class Program
    {    
        static void Main(string[] args)
        {
            CoalescingOp();
            Console.ReadKey();
        }

        static void CoalescingOp()
        {
            // A nullable int
            int? x = null;
            // Assign x to y.
            // y = x, unless x is null, in which case y = -33(an integer selected by our own choice)
            int y = x ?? -33;
            Console.WriteLine("When x = null, then y = " + y.ToString());

            x = 10;
            y = x ?? -33;
            Console.WriteLine("When x = 10, then y = " + y.ToString());    
        }
    }
}
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Rauf
  • 12,326
  • 20
  • 77
  • 126
0

It's the null coalescing operator.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445