Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

The ?? Operator

4.50/5 (27 votes)
4 Sep 2012CPOL 96.2K  
This operator is introduced to set value in place of null value, it can also be defined in words like 'In case of null, pick value from another'

Introduction

Operator is introduced with Nullable datatype inclusion in .NET Framework operator ?? can also be referred in words like 'In case of null, pick value from another'.

Scenario

Suppose you're assigning a value to Nullable bool like:

C#
bool? b = null;
At the time of checking value, it will give you an error like:

C#
if(b) //Error CS0266.
{
 
}

So it's always preferable to use ?? to prevent error like:

C#
if(b ?? false)
{
}

It defines that, in case b is null, pick the value false.

?? can also be used in multiple choice of value like:

C#
bool ? a = null
bool ? b = null
bool ? c = true
 
a = b ?? c ?? false;

That will check b first if b is undefined or null, then it will move further to check for c if that also has null then it will set false to a.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)