Null Coalescing Operator To Define Default Value For Nullable Types – Double Question Mark

We all know that defining a nullable type in C# is very simple as below

int? value;

And when you want to check whether the value is null, then there are definitely multiple way you could do.

// First option.
if(value == null)
{
    //Write the code here
}

// Second Option.
if(!value.HasValue)
{
   //Write the code here
}

However there is a easy way you could specify the default value i.e., the default value to be used in case the nullable type has a null value in it.
below code block will set the index to 10 if value is null.

	
int index = value ?? 10;

Below code block will check for both value1 and value2 for null and then assigns the value as null.

int index = value1 ?? value2 ?? 10;
Jebarson

Jebarson is a consultant at Microsoft. In his overall experience of 7+ years, his expertise ranges from VB6, COM / DCOM, .net, ASP.net, WPF, WCF, SL, SQL. He has a greater love for OOA / OOD and SOA. His current focus is on Azure, Windows Phone 7, Crm and much more. He is also a frequent speaker of different community events. He blogs at http://www.jebarson.info/ . You can follow him at @Jebarson007 . Jebarson having good set of tutorials written on Windows Azure, you can found them http://bit.ly/houBNx . He is a contributor of this site and shared many tips and tricks.

One Comment to “Null Coalescing Operator To Define Default Value For Nullable Types – Double Question Mark”

  1. you’re really a good webmaster. The site loading pace is amazing. It seems that you are doing any distinctive trick. Furthermore, The contents are masterwork. you’ve performed a fantastic activity on this matter!

Comments are closed.