开发者

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

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开发者_如何学Go documentation for as wrong? Am I missing something?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜