Edward Tanguay Edward Tanguay - 6 months ago 29
C# Question

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.

lc. lc.

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;
    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:

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