What is ' ?? ' operator ?

 Posted by Ddd on 1/26/2011 | Category: C# Interview questions | Views: 4342 | Points: 40
Answer:

It is also called as the null coalescing operator.
It evaluates which value will be assigned to a variable of a particular type if we have 2 variables
of a particular type(nullable or a reference type).

The 1st input variable must be a nullable or a reference type.
The 2nd input variable should be of the same type as the first one or of a type that can be implicitly
converted to the type of the first variable.


input 1 input 2 target
null not null value of 2nd input
not null null value of 1st input
not null not null value of 1st input
null null null
example:
class Class2
{
static void Main()
{
int? a = null;
int b;
int c=30;

b=a ?? c;
Console.WriteLine(b);
//b is 30 as a is null
a = 35;
b = a ?? c;
Console.WriteLine(b);
//b is 35 as a is now assigned 35 value
}

}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response