Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

I read:

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

And boxing conversions.....

Just a guess, but I'd say it boxes o as an integer and then converts it to a nullable.

From the documentation about the as keyword:

It is equivalent to the following expression except that expression is evaluated only one time.

expression is type ? (type)expression : (type)null

The reference for is use also states it works with reference types, however, you can also do stuff like this:

int? temp = null;
if (temp is int?)
{
    // Do something
}

I'm guessing it is just an inaccuracy in the reference documentation in that the type must be nullable (ie a nullable type or a reference type) instead of just a reference type.

Apparently the MSDN documentation on the as operator needs to be updated.

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

If you try the following code where we use the as operator with the value type int, you get the appropriate compiler error message that

The as operator must be used with a reference type or nullable type ('int' is a non-nullable value type)

There is an update though on the link in Community Content section that quotes:

The as operator must be used with a reference type or nullable type.

You're applying the 'as' to Object, which is a reference type. It could be null, in which case the CLR has special support for unboxing the reference 'null' to a nullable value type. This special unboxing is not supported for any other value type, so, even though Nullable is a value type, it does have certain special privledges.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top