24

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

Hi, I was looking for some trainings of MVC 2 in C# and I found this sintax:

ViewData["something"] = something ?? true;

So, what is that '??' means ?.

Community
  • 1
  • 1
pjnovas
  • 1,086
  • 1
  • 8
  • 24
  • 7
    Duplicate question of http://stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c ? – Crag Sep 28 '10 at 18:08
  • 1
    Sorry, I've searched for it and I couldn't found it, so I posted it. Thanks a lot to all of you guys! I love this page, there is an answer for everything :D – pjnovas Sep 28 '10 at 18:18

3 Answers3

39

It's the null-coalescing operator.

It returns the first argument unless it is null, in which case it returns the second.

x ?? y is roughly equivalent to this (except that the first argument is only evaluated once):

if (x == null)
{
     result = y;
}
else
{
     result = x;
}

Or alternatively:

(x == null) ? y : x

It is useful for providing a default value for when a value can be null:

Color color = user.FavouriteColor ?? defaultColor;

COALESCE

When used in a LINQ to SQL query the ?? operator can be translated to a call to COALESCE. For example this LINQ query:

var query = dataContext.Table1.Select(x => x.Col1 ?? "default");

can result in this SQL query:

SELECT COALESCE([t0].[col1],@p0) AS [value]
FROM [dbo].[table1] AS [t0]
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
7

It is the null coalescing operator. The return value is the left hand side if it is non-null and the right hand side otherwise. It works for both reference types and nullables

var x = "foo" ?? "bar";  // "foo" wins
string y = null;
var z = y ?? "bar"; // "bar" wins
int? n = null;
var t = n ?? 5;  // 5 wins
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

If something is null, it returns true, otherwise it returns something. See this link for more.

JoshD
  • 12,490
  • 3
  • 42
  • 53