Table of Contents 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Notes DownloadECMA-334 C# Language Specification 14 Expressions 14.9 Relational and type-testing operators 14.9.10 The as operator
Paragraph 11 The as operator is used to explicitly convert a value to a given reference type using a reference conversion or a boxing conversion. 2 Unlike a cast expression (§14.6.6), the as operator never throws an exception. 3 Instead, if the indicated conversion is not possible, the resulting value is null.
Paragraph 21 In an operation of the form e as T, e must be an expression and T must be a reference type. 2 The type of the result is T, and the result is always classified as a value. 3 The operation is evaluated as follows:
Paragraph 31 Note that the as operator only performs reference conversions and boxing conversions. 2 Other conversions, such as user defined conversions, are not possible with the as operator and should instead be performed using cast expressions.
- 4 If the compile-time type of e is the same as T, the result is simply the value of e.
- 5 Otherwise, if an implicit reference conversion (§13.1.4) or boxing conversion (§13.1.5) exists from the compile-time type of e to T, this conversion is performed and becomes the result of the operation.
- 6 Otherwise, if an explicit reference conversion (§13.2.3) exists from the compile-time type of e to T, a dynamic type check is performed:
- 7 If the value of e is null, the result is the value null with the compile-time type T.
- 8 Otherwise, let R be the run-time type of the instance referenced by e. 9 If R and T are the same type, if R is a reference type and an implicit reference conversion from R to T exists, or if R is a value type and T is an interface type that is implemented by R, the result is the reference given by e with the compile-time type T.
- 10 Otherwise, the result is the value null with the compile-time type T.
- 11 Otherwise, the indicated conversion is never possible, and a compile-time error occurs.
|Jagger Software Ltd|
|Company # 4070126|
|VAT # 762 5213 42|