Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

c# - Why can the 'as' operator not be used to parse non-nullable value types?

Every Developer has his/her own standards. Some developers like to <type>.TryParse(), some developers like to cast using (type)object;, and some developers love using the keywords instead.

I noticed a hiccup with the 'as' operator - you cannot use it to perform conversions between non-nullable value types. I read the documentation on MSDN on the as Keyword and they also explain it as "You can use the as operator to perform certain types of conversions between compatible reference types or nullable types."

I tested this with the following:

                    int i = 0;
                    var k = i as int; //Breaks

                    int i = 0;
                    var k = i as int?; //Works

What were the reasons decided for the as keyword to perform in this way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

as operator would return null if parsing fails. Since int is a non nullable value type, you get the error, whereas int? or Nullable<int> can hold null value, that is why your second code snippet works.

See: as (C# Reference)

You can use the as operator to perform certain types of conversions between compatible reference types or nullable types

also from the same doc link

The as operator is like a cast operation. However, if the conversion isn't possible, as returns null instead of raising an exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...