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

前端 未结 1 1472
时光取名叫无心
时光取名叫无心 2021-01-18 19:41

Every Developer has his/her own standards. Some developers like to .TryParse(), some developers like to cast using (type)object;, and s

相关标签:
1条回答
  • 2021-01-18 20:23

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题