#1,045 – Implicit Conversions When Assigning from a Nullable Type
March 4, 2014 1 Comment
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;