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

寵の児 提交于 2019-12-01 19:39:45

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!