#1,045 – Implicit Conversions When Assigning from a Nullable Type

Implicit conversions are allowed when converting from a value type to its associated nullable type.  Implicit conversions are not allowed in the other direction, however, from nullable type to corresponding value type.  This is because the range of the nullable type is greater than the range of the associated value type.  That is, the conversion may result in a loss of data.  You must either use an explicit conversion or access the underlying value using the Value property.

            int anInt = 12;

            // Allowed - implicit conversion to nullable type
            int? nullableInt = anInt;

            // Also allowed, since implicit conversion from int to long
            // is allowed
            long? nullableLong = anInt;

            // Implicit conversion not allowed
            //int newInt = nullableInt;

            // Must do explicit conversion
            int newInt = (int)nullableInt;

            // Better
            newInt = nullableInt.HasValue ? nullableInt.Value : 0;

            // long? = int? implicit conversion IS allowed
            nullableLong = nullableInt;

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,045 – Implicit Conversions When Assigning from a Nullable Type

  1. Pingback: Dew Drop – March 5, 2014 (#1735) | 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 )

Connecting to %s

%d bloggers like this: