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

后端 未结 7 1206
误落风尘
误落风尘 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条回答
  •  Happy的楠姐
    2020-12-13 02:18

    Because sometimes you want things to fail if you can't cast like you expect, and other times you don't care and just want to discard a given object if it can't cast.

    It's basically a faster version of a regular cast wrapped in a try block; but As is far more readable and also saves typing.

提交回复
热议问题