6

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

Community
  • 1
  • 1

4 Answers4

12

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
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
saj
  • 4,626
  • 2
  • 26
  • 25
  • Is this just a c# feature, or is this a standard feature of most programming languages? – Thomas Clayson Aug 23 '12 at 13:51
  • As nullable types are a feature of .NET/C#, this is C# specific. While Visual Basic.NET of course knows nullable types, too, the `??` operator and the ternary operator are not available there. Other languages may also have a `??` operator, however, it may have a totally different meaning. – Thorsten Dittmar Aug 23 '12 at 13:52
  • As far as I know it's a c# feature – saj Aug 23 '12 at 13:53
  • @ThorstenDittmar : VB supports both a ternary operation and null coalescing operation using the IF conditional operator. Passing 3 operands to the If operator is the conditional form like C#'s ?: and passing 2 operands is like C#'s ?? operator. See section 11.22 of the VB language spec. – Chris Dunaway Aug 23 '12 at 14:45
  • I didn't say that VB doesn't support nullable types (Saying nullable types are a feature of .NET/C# is misleading, I agree. They are a feature of .NET). In fact I said it did, because it's a .net language. Great to hear there's the IF operator, but `??` and `?` are not available. I wanted to say that this special syntax was C# only - the feature itself is not and could easily be replicated in any given programming language using a function and the full `if` statement `saj` gave above. – Thorsten Dittmar Aug 23 '12 at 14:50
2
if(x == null)
     y = 5
else
     y = x
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
1

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.

JeffFerguson
  • 2,952
  • 19
  • 28
0

Yes This is if else statement. Have a look of this URL http://www.webofideas.co.uk/Blog/c-sharp-double-question-mark-syntax.aspx