14.15 Constant expressions

A constant-expression is an expression that can be fully evaluated at
compile-time.
constant-expression:
expression
The type of a constant expression can be one of the following: sbyte, byte,
short, ushort, int, uint,
long, ulong, char, float, double, decimal, bool, string, any enumeration
type, or the null type.
The following constructs are permitted in constant expressions:
?Literals (including the null literal).
?References to const members of class and struct types.
?References to members of enumeration types.
C# LANGUAGE SPECIFICATION
176
?Parenthesized sub-expressions, which are themselves constant expressions.
?Cast expressions, provided the target type is one of the types listed
above.
?The predefined +, -, !, and ~ unary operators.
?The predefined +, -, *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=,
and >= binary operators, provided
each operand is of a type listed above.
?The ?: conditional operator.
Whenever an expression is of one of the types listed above and contains
only the constructs listed above, the
expression is evaluated at compile-time. This is true even if the
expression is a sub-expression of a larger
expression that contains non-constant constructs.
The compile-time evaluation of constant expressions uses the same rules as
run-time evaluation of nonconstant
expressions, except that where run-time evaluation would have thrown an
exception, compile-time
evaluation causes a compile-time error to occur.
Unless a constant expression is explicitly placed in an unchecked context,
overflows that occur in integraltype
arithmetic operations and conversions during the compile-time evaluation of
the expression always
cause compile-time errors (?4.5.12).
Constant expressions occur in the contexts listed below. In these contexts,
a compile-time error occurs if an
expression cannot be fully evaluated at compile-time.
?Constant declarations (?7.3).
?Enumeration member declarations (?1.30).
?case labels of a switch statement (?5.7.2).
?goto case statements (?5.9.3).
?Dimension lengths in an array creation expression (?4.5.10.2) that
includes an initializer.
?Attributes (?4).
An implicit constant expression conversion (?3.1.6) permits a constant
expression of type int to be
converted to sbyte, byte, short, ushort, uint, or ulong, provided the value
of the constant expression
is within the range of the destination type.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值