Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ?? operator means in C#? [duplicate]

Tags:

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 ?.

like image 534
pjnovas Avatar asked Sep 28 '10 18:09

pjnovas


People also ask

What are operators in C?

An operator is a symbol that operates on a value or a variable. For example: + is an operator to perform addition. C has a wide range of operators to perform various operations.

What is operator and its types in C?

Summary. An operator is a symbol which operates on a variable or value. There are types of operators like arithmetic, logical, conditional, relational, bitwise, assignment operators etc. Some special types of operators are also present in C like sizeof(), Pointer operator, Reference operator etc.

What does &= mean in C?

It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.


1 Answers

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] 
like image 70
Mark Byers Avatar answered Sep 19 '22 06:09

Mark Byers