6

Possible Duplicate:
What is the “??” operator for?

Please explain me what is use of "??" in below code and what is "??" used for.

if ((this.OrderDate ?? DateTime.MinValue) > DateTime.Today)

{ e.Description = "The Order Date must not be in the future."; return false; }

the above code is at http://nettiers.com/EntityLayer.ashx

Thanks.

Community
  • 1
  • 1
Dr. Rajesh Rolen
  • 14,029
  • 41
  • 106
  • 178
  • 3
    `??` as such might be hard to search for, but searching for "C# syntax" or "C# operators" pretty quickly gets you to the answers. – Dirk Vollmar Oct 05 '10 at 09:26

1 Answers1

9

(This is a duplicate, but it's hard to search for, so I'm happy enough to provide more another target for future searches...)

It's the null-coalescing operator. Essentially it evaluates the first operand, and if the result is null (either a null reference or the null value for a nullable value type) then it evaluates the second operand. The result is whichever operand was evaluated last, effectively.

Note that due to its associativity, you can write:

int? x = E1 ?? E2 ?? E3 ?? E4;

if E1, E2, E3 and E4 are all expressions of type int? - it will start with E1 and progress until it finds a non-null value.

The first operand has to be a nullable type, but e second operand can be non-nullable, in which case the overall expression type is non-nullable. For example, suppose E4 is an expression of type int (but all the rest are still int? then you can make x non-nullable:

int x = E1 ?? E2 ?? E3 ?? E4;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194