Why can the as operator be used with Nullable<T>?

recursive picture recursive · Aug 18, 2011 · Viewed 7k times · Source

According to the documentation of the as operator, as "is used to perform certain types of conversions between compatible reference types". Since Nullable is actually a value type, I would expect as not to work with it. However, this code compiles and runs:

object o = 7;
int i = o as int? ?? -1;
Console.WriteLine(i); // output: 7

Is this correct behavior? Is the documentation for as wrong? Am I missing something?

Answer

Eric Lippert picture Eric Lippert · Aug 18, 2011

Is this correct behavior?

Yes.

Is the documentation for as wrong?

Yes. I have informed the documentation manager. Thanks for bringing this to my attention, and apologies for the error. Obviously no one remembered to update this page when nullable types were added to the language in C# 2.0.

Am I missing something?

You might consider reading the actual C# specification rather than the MSDN documentation; it is more definitive.