#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;
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,054 – Implicit Conversions from Constant Expressions

  1. Pingback: Dew Drop – March 17, 2014 (#1744) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: