88

Possible Duplicates:
?? Null Coalescing Operator --> What does coalescing mean?
What do two question marks together mean in C#?

I couldn't find this question being asked here so I figured I would ask it. What does a double question mark do in C#?

Example:

x = y ?? z;
Dharman
  • 30,962
  • 25
  • 85
  • 135
tom d
  • 1,023
  • 1
  • 8
  • 10
  • this has been asked a few times: http://stackoverflow.com/questions/1064074/operator-in-c/ http://stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c – Kirschstein Oct 22 '09 at 15:54
  • 1
    http://stackoverflow.com/questions/827454/ – John Gietzen Oct 22 '09 at 15:54
  • It gets you, and everyone who answers before the topic is closed, a lot of rep :) [It always amazes me how fast null coalescing questions and answer get rep here...] – Reed Copsey Oct 22 '09 at 15:55
  • Ya, I thought i was gonna make big coin, but I had a brainfart and couldn't remember the dang jargon in time. Baw. –  Oct 22 '09 at 16:00

7 Answers7

101

This is a null coalescing operator. The method above states x is assigned y's value, unless y is null, in which case it is assigned z's value.

Alexis Abril
  • 6,389
  • 6
  • 33
  • 53
31

From Wikipedia:

It's the null-coalesce operator and shorthand for this:

x = (y != null ? y : z);
Austin Salonen
  • 49,173
  • 15
  • 109
  • 139
24

Use y if not null, otherwise use z.

Jeankowkow
  • 814
  • 13
  • 33
CodeSpeaker
  • 810
  • 8
  • 22
12

If a the value y is null then the value z is assigned.

For example:

x = Person.Name ?? "No Name";

If name is null x will have the value "No Name"

Michael Edwards
  • 6,308
  • 6
  • 44
  • 75
8

If y is null x will be set to z.

Spencer Ruport
  • 34,865
  • 12
  • 85
  • 147
1

As others have stated, it is the null coalescing operator.

MSDN information on this:

https://learn.microsoft.com/dotnet/csharp/language-reference/operators/null-coalescing-operator

Madis Otenurm
  • 61
  • 1
  • 7
itsmatt
  • 31,265
  • 10
  • 100
  • 164
1

.Net framework 2.0 onwards allow null values to Nullable value types.

here in this case, it says x equals y if it has some value (ie not null) or else equals z

123Developer
  • 1,463
  • 3
  • 17
  • 24