#1,054 – Implicit Conversions from Constant Expressions

A constant expression is an expression whose type and value can be determined at compile-time.  Integer literals are one form of a constant expression, with the type inferred based on the value of the literal (and the use of u and/or suffixes).

Recall that implicit numeric conversions are not allowed if the full range of values in the expression is not allowed in the target type.  For example, you can’t do an implicit conversion from a variable of type int to a byte, even if the variable contains a value that could be stored in a byte.

            int i = 1;

            // Implicit conversion not allowed,
            // i.e. requires a cast
            byte b = i;

Implicit conversions from constant expressions, however, are allowed as long as the value is within the range of the target type. Since the compiler knows the value at compile-time, it can make this determination.

For example, an integer literal whose value of 1 will be of type int, but is implicitly convertible to a variable of type byte.

            // Literal 1 is of type
            // int (inferred by compiler),
            // but can be implicitly converted
            // to byte.
            byte b2 = 1;