Edward Tanguay
Edward Tanguay

Reputation: 193402

What do two question marks together mean in C#?

Ran across this line of code:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

What do the two question marks mean, is it some kind of ternary operator? It's hard to look up in Google.

Upvotes: 2032

Views: 731067

Answers (18)

NolePTR
NolePTR

Reputation: 304

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

is equivalent to

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

But the cool thing about it is you can chain them, like other people said. The one thing not touched upon is that you can actually use it to throw an exception.

A = A ?? B ?? throw new Exception("A and B are both NULL");

Upvotes: 3

D'Arcy Rittich
D'Arcy Rittich

Reputation: 171539

?? is there to provide a value for a nullable type when the value is null. So, in your example:

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

If formsAuth is null, the expression will return new FormsAuthenticationWrapper() to be assigned to FormsAuth.

Upvotes: 26

Shahid Riaz Bhatti
Shahid Riaz Bhatti

Reputation: 421

In the simplest terms, two question marks are called the "null coalescing operator", which returns the first non-null value from the expression chain.

E.g. if you are taking a value from a nullable object and assigning it to a variable which is not nullable, then you can use this operator. i.e.

int a = 1;
int? b = null;
a = b ?? 0;

The result in the above equation stored in a would be zero, because b is null and we have used the ?? operator along with zero, which means that it will return "0" if and only if b is null.

int a = 1; 
int? b = 15;
a = b ?? 0;

In above equation, a will get value "15" because b has a valid value and is not null.
Also, you can not use ?? operator on a non nullable object.

In above examples, I used ?? 0, however a complete new equation can also be used after ?? operator, such as:

a = b ?? (x == 1 ? 10 : 15)

Upvotes: 8

Thane Plummer
Thane Plummer

Reputation: 10328

Others have described the "null-coalescing operator" quite well. In cases where a single test for null is required, the shortened syntax afforded by the closely related null-coalescing assignment operator ??= can add further readability (at least for C# 8.0 and later).

Legacy null test:

if (myvariable == null)
{
    myvariable = new MyConstructor();
}

Using the null-coalescing operator this can be rewritten as:

myvariable = myvariable ?? new MyConstructor();

Which can also be written with null-coalescing assignment:

myvariable ??= new MyConstructor();

Some find it more readable and succinct.

Upvotes: 19

Jubayer Hossain
Jubayer Hossain

Reputation: 89

The ?? operator is called the null-coalescing operator. It returns the left-hand operand if the operand is not null; otherwise it returns the right hand operand.

int? variable1 = null;
int variable2  = variable1 ?? 100;

Set variable2 to the value of variable1, if variable1 is NOT null; otherwise, if variable1 == null, set variable2 to 100.

Upvotes: 3

lc.
lc.

Reputation: 116528

It's the null coalescing operator, and quite like the ternary (immediate-if) operator. See also ?? Operator - MSDN.

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

expands to:

FormsAuth = formsAuth != null ? formsAuth : new FormsAuthenticationWrapper();

which further expands to:

if(formsAuth != null)
    FormsAuth = formsAuth;
else
    FormsAuth = new FormsAuthenticationWrapper();

In English, it means "If whatever is to the left is not null, use that, otherwise use what's to the right."

Note that you can use any number of these in sequence. The following statement will assign the first non-null Answer# to Answer (if all Answers are null then the Answer is null):

string Answer = Answer1 ?? Answer2 ?? Answer3 ?? Answer4;

Also it's worth mentioning while the expansion above is conceptually equivalent, the result of each expression is only evaluated once. This is important if for example an expression is a method call with side effects. (Credit to @Joey for pointing this out.)

Upvotes: 2671

Shivprasad Koirala
Shivprasad Koirala

Reputation: 28666

enter image description here

The two question marks (??) indicate that its a Coalescing operator.

Coalescing operator returns the first NON-NULL value from a chain. You can see this youtube video which demonstrates the whole thing practically.

But let me add more to what the video says.

If you see the English meaning of coalescing it says “consolidate together”. For example below is a simple coalescing code which chains four strings.

So if str1 is null it will try str2, if str2 is null it will try str3 and so on until it finds a string with a non-null value.

string final = str1 ?? str2 ?? str3 ?? str4;

In simple words Coalescing operator returns the first NON-NULL value from a chain.

Upvotes: 34

Ashish Mishra
Ashish Mishra

Reputation: 687

It's a null coalescing operator that works similarly to a ternary operator.

    a ?? b  => a !=null ? a : b 

Another interesting point for this is, "A nullable type can contain a value, or it can be undefined". So if you try to assign a nullable value type to a non-nullable value type you will get a compile-time error.

int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.

So to do that using ?? operator:

z = x ?? 1; // with ?? operator there are no issues

Upvotes: 1

brakeroo
brakeroo

Reputation: 1467

As correctly pointed in numerous answers that is the "null coalescing operator" (??), speaking of which you might also want to check out its cousin the "Null-conditional Operator" (?. or ?[) that is an operator that many times it is used in conjunction with ??

Null-conditional Operator

Used to test for null before performing a member access (?.) or index (?[) operation. These operators help you write less code to handle null checks, especially for descending into data structures.

For example:

// if 'customers' or 'Order' property or 'Price' property  is null,
// dollarAmount will be 0 
// otherwise dollarAmount will be equal to 'customers.Order.Price'

int dollarAmount = customers?.Order?.Price ?? 0; 

the old way without ?. and ?? of doing this is

int dollarAmount = customers != null 
                   && customers.Order!=null
                   && customers.Order.Price!=null 
                    ? customers.Order.Price : 0; 

which is more verbose and cumbersome.

Upvotes: 13

Jon Skeet
Jon Skeet

Reputation: 1503080

Just because no-one else has said the magic words yet: it's the null coalescing operator. It's defined in section 7.12 of the C# 3.0 language specification.

It's very handy, particularly because of the way it works when it's used multiple times in an expression. An expression of the form:

a ?? b ?? c ?? d

will give the result of expression a if it's non-null, otherwise try b, otherwise try c, otherwise try d. It short-circuits at every point.

Also, if the type of d is non-nullable, the type of the whole expression is non-nullable too.

Upvotes: 333

KingOfHypocrites
KingOfHypocrites

Reputation: 9537

Some of the examples here of getting values using coalescing are inefficient.

What you really want is:

return _formsAuthWrapper = _formsAuthWrapper ?? new FormsAuthenticationWrapper();

or

return _formsAuthWrapper ?? (_formsAuthWrapper = new FormsAuthenticationWrapper());

This prevents the object from being recreated every time. Instead of the private variable remaining null and a new object getting created on every request, this ensures the private variable is assigned if the new object is created.

Upvotes: 9

dqninh
dqninh

Reputation: 109

Nothing dangerous about this. In fact, it is beautiful. You can add default value if that is desirable, for example:

CODE

int x = x1 ?? x2 ?? x3 ?? x4 ?? 0;

Upvotes: 10

aku
aku

Reputation: 124034

coalescing operator

it's equivalent to

FormsAuth = formsAUth == null ? new FormsAuthenticationWrapper() : formsAuth

Upvotes: 11

Sarah Vessels
Sarah Vessels

Reputation: 31660

If you're familiar with Ruby, its ||= seems akin to C#'s ?? to me. Here's some Ruby:

irb(main):001:0> str1 = nil
=> nil
irb(main):002:0> str1 ||= "new value"
=> "new value"
irb(main):003:0> str2 = "old value"
=> "old value"
irb(main):004:0> str2 ||= "another new value"
=> "old value"
irb(main):005:0> str1
=> "new value"
irb(main):006:0> str2
=> "old value"

And in C#:

string str1 = null;
str1 = str1 ?? "new value";
string str2 = "old value";
str2 = str2 ?? "another new value";

Upvotes: 13

Edward Tanguay
Edward Tanguay

Reputation: 193402

Thanks everybody, here is the most succinct explanation I found on the MSDN site:

// y = x, unless x is null, in which case y = -1.
int y = x ?? -1;

Upvotes: 40

blabla999
blabla999

Reputation: 3200

For your amusement only (knowing you are all C# guys ;-).

I think it originated in Smalltalk, where it has been around for many years. It is defined there as:

in Object:

? anArgument
    ^ self

in UndefinedObject (aka nil's class):

? anArgument
    ^ anArgument

There are both evaluating (?) and non-evaluating versions (??) of this.
It is often found in getter-methods for lazy-initialized private (instance) variables, which are left nil until really needed.

Upvotes: 9

Iain Holder
Iain Holder

Reputation: 14262

It's the null coalescing operator.

http://msdn.microsoft.com/en-us/library/ms173224.aspx

Yes, nearly impossible to search for unless you know what it's called! :-)

EDIT: And this is a cool feature from another question. You can chain them.

Hidden Features of C#?

Upvotes: 81

Benjamin Autin
Benjamin Autin

Reputation: 4171

It's short hand for the ternary operator.

FormsAuth = (formsAuth != null) ? formsAuth : new FormsAuthenticationWrapper();

Or for those who don't do ternary:

if (formsAuth != null)
{
  FormsAuth = formsAuth;
}
else
{
  FormsAuth = new FormsAuthenticationWrapper();
}

Upvotes: 18

Related Questions