Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this an if else statement [duplicate]

Possible Duplicate:
What do two question marks together mean in C#?

I just came across the code below and not really sure what it means and can't google it because google omits the ??

int? x = 32;
int  y = x ?? 5;

Is the second line some sort of if else statement, what does the ?? mean

like image 442
user1619910 Avatar asked Aug 23 '12 13:08

user1619910


People also ask

Is the replacement of if else statement?

The Ternary Operator One of my favourite alternatives to if...else is the ternary operator. Here expressionIfTrue will be evaluated if condition evaluates to true ; otherwise expressionIfFalse will be evaluated. The beauty of ternary operators is they can be used on the right-hand side of an assignment.

How to avoid code duplication in c#?

Take all the common parts of the classes, and create an abstract base class from them. Leave the SetTestClass method abstract . Show activity on this post. Create a separate project with this class and a "base implementation" for the methods.


3 Answers

It's called the null-coalescing operator.

If the value to the left of the ?? is null, then use the value to the right of the ?? otherwise use the left hand value.

Expanded out:

y = x == null ? 5 : x

or

if(x == null)
     y = 5
else
     y = x
like image 123
saj Avatar answered Oct 04 '22 01:10

saj


if(x == null)
     y = 5
else
     y = x
like image 31
Aghilas Yakoub Avatar answered Oct 04 '22 01:10

Aghilas Yakoub


The ?? operator is used with a collection of variables and evaluates to the value of the first non-null variable. For example, consider the following code:

int? x = null;
int? y = null;
int? z = null;

y = 12;
int? a = x ?? y ?? z;

The value of a will be 12, because y is the first variable in the statement with a non-null value.

like image 42
JeffFerguson Avatar answered Oct 04 '22 01:10

JeffFerguson