Consider the following::
Object box = 5;
int @int = (int)box; // int = 5
int? nullableInt = box as int?; // nullableInt = 5;
StringComparison @enum = (StringComparison)box; // enum = OrdinalIgnoreCase
StringComparison? nullableEnum = box as StringComparison?; // nullableEnum = null.
2 things::
- Why can I unbox to
StringComparison
? I guess this is because it's underlying type isInt32
but I still find it odd. - Why does
nullableEnum
have a value of null?
As I understand the only valid unboxing is from a boxed value type is to it's type or to a nullable type. If int
can unbox to Enum
, then why doesn't the same hold true for the nullable values? Similarly, if Instead of 5 I boxed StringComparison.OrdinalIgnoreCase
, it would be that nullableInt
would be null, but nullableEnum
would not be.