Tuesday, June 21, 2011

The double question mark operator in C#

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.
// if x is equal to null, then y = x. Otherwise 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());

}
}
}


Output
-------

No comments:

Post a Comment