ECMA-334 C# Language Specification14.6.6: Cast expressions |
A cast-expression
is used to explicitly convert an expression to a given type.
(
type
)
unary-expression
A cast-expression
of the form (T)E, where T is a type and E is a unary-expression
, performs an explicit conversion (13.2) of the value of E to type T. If no explicit conversion exists from the type of E to T, a compile-time error occurs. Otherwise, the result is the value produced by the explicit conversion. The result is always classified as a value, even if E denotes a variable.
The grammar for a cast-expression
leads to certain syntactic ambiguities. For example, the expression (x)-y could either be interpreted as a cast-expression
(a cast of -y to type x) or as an additive-expression
combined with a parenthesized-expression
(which computes the value x -y).
To resolve cast-expression
ambiguities, the following rule exists: A sequence of one or more tokens (9.4) enclosed in parentheses is considered the start of a cast-expression
only if at least one of the following are true:
cast-expression
is it considered a cast-expression
. end note]
The term "correct grammar" above means only that the sequence of tokens must conform to the particular grammatical production. It specifically does not consider the actual meaning of any constituent identifiers. For example, if x and y are identifiers, then x.y is correct grammar for a type, even if x.y doesn't actually denote a type.
cast-expression
s, but (x)-y is not, even if x identifies a type. However, if x is a keyword that identifies a predefined type (such as int ), then all four forms are cast-expression
s (because such a keyword could not possibly be an expression by itself). end note]