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

后端 未结 7 1217
误落风尘
误落风尘 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:10

    They aren't two system of casting. The two have similar actions but very different meanings. An "as" means "I think this object might actually be of this other type; give me null if it isn't." A cast means one of two things:

    • I know for sure that this object actually is of this other type. Make it so, and if I'm wrong, crash the program.

    • I know for sure that this object is not of this other type, but that there is a well-known way of converting the value of the current type to the desired type. (For example, casting int to short.) Make it so, and if the conversion doesn't actually work, crash the program.

    See my article on the subject for more details.

    https://ericlippert.com/2009/10/08/whats-the-difference-between-as-and-cast-operators/

提交回复
热议问题