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

By | March 18, 2011

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;

One thought on “Null Coalescing Operator To Define Default Value For Nullable Types – Double Question Mark

  1. dom na sprzedaż

    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.