首页 > 代码库 > C# - as

C# - as



You can use the as operator to perform certain types of conversions between compatible reference types ornullable types.

The as operator is like a cast operation. However, if the conversion isn‘t possible,as returns null instead of raising an exception. Consider the following example:

expression as type

The code is equivalent to the following expression except that theexpression variable is evaluated only one time.

expression is type ? (type)expression : (type)null
Note that theas operator performs only reference conversions, nullable conversions, and boxing conversions. Theas operator can‘t perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

C# - as