What's the point of “As” keyword in C#

后端 未结 7 1182
误落风尘
误落风尘 2020-12-13 01:32

From the docs:

The as operator is like a cast except that it yields null on conversion failure instead of raising an exception. More formally, an exp

相关标签:
7条回答
  • 2020-12-13 02:22

    I generally choose one or the other based on the semantics of the code.

    For example, if you have an object that you know that it must be an string then use (string) because this expresses that the person writing the code is sure that the object is a string and if it's not than we already have bigger problems than the runtime cast exception that will be thrown.

    Use as if you are not sure that the object is of a specific type but want to have logic for when it is. You could use the is operator followed by a cast, but the as operator is more efficient.

    0 讨论(0)
提交回复
热议问题