C# 2.0 null coalescing operator

Have you ever heard of an operator like ??. No !  I won’t be surprised, because it is implemented in .C# 2.0. This is termed as null coalescing operator.
First when I see this, I was totally surprised and done a search to find it out. But nothing was coming up in MSDN sites. In this post we will see how this new operator can be used. See the following sample

class Program
{
static void Main(string[] args)
{
string strName = null;
Console.WriteLine(strName ?? "This is null");
Console.WriteLine(strName == null ? "This is null" : strName); //This is similar to the above line
Console.ReadLine();
}
}

Above code shows how we can make use of ?? operator,  See the code below which shows another type of implementation

class Program
{
static void Main(string[] args)
{
MyClass obj = null;
if (obj == null)
obj =  new MyClass(); //Using if

obj = obj ?? new MyClass(); //same checking using ?? operator

Console.ReadLine();
}
}

class MyClass
{

}

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