8

I'm looking at the generated code by ASP.NET MVC 1.0, and was wondering; what do the double question marks mean?

// This constructor is not used by the MVC framework but is instead provided for ease
// of unit testing this type. See the comments at the end of this file for more
// information.
public AccountController(IFormsAuthentication formsAuth, IMembershipService service)
{
    FormsAuth = formsAuth ?? new FormsAuthenticationService();
    MembershipService = service ?? new AccountMembershipService();
}

Related:

?? Null Coalescing Operator —> What does coalescing mean?

Community
  • 1
  • 1
Brian Liang
  • 7,734
  • 10
  • 57
  • 72
  • 1
    This is a duplicate, but also notoriously hard to google for – Dana Apr 20 '09 at 21:17
  • 1
    possible duplicate of [What do two question marks together mean in C#?](http://stackoverflow.com/questions/446835/what-do-two-question-marks-together-mean-in-c) – Narkha Jan 20 '14 at 16:53

6 Answers6

32

This is the null-coalescing operator. It will return the value on its left if that value is not null, else the value on the right (even if it is null). They are often chained together ending in a default value.

Check out this article for more

bdukes
  • 152,002
  • 23
  • 148
  • 175
JoshJordan
  • 12,676
  • 10
  • 53
  • 63
10

It means the same as

If (formsAuth != null)
  FormsAuth = formsAuth;
else
  FormsAuth = FormsAuthenticationService();
Nathan W
  • 54,475
  • 27
  • 99
  • 146
2

it's the null-coalescing operator

From MSDN

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

A nullable type can contain a value, or it can be undefined. The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

For more information, see Nullable Types (C# Programming Guide).

The result of a ?? operator is not considered to be a constant even if both its arguments are constants.

Russ Cam
  • 124,184
  • 33
  • 204
  • 266
2

It's the null coalescing operator. If the value on the left is null, it will return the value on the right.

Pang
  • 9,564
  • 146
  • 81
  • 122
James Avery
  • 3,062
  • 1
  • 20
  • 26
1

If formsAuth it is null it returns the value on the right ( new FormsAuthenticationService() ).

Otávio Décio
  • 73,752
  • 17
  • 161
  • 228
0

It means : return the first value (e.g. "formsAuth") if it's NOT NULL, or else the second value (new FormsAuthenticationService()):

Marc

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459