Why is a collection of enum unable to cast to an int?
enum Test { A = 1, B = 2 };
int? x = (int?)Test.A; // Valid
var collection1 = new[] { Test.A }.Cast<int>().ToList();
// InvalidCastException has thrown (Specified cast is not valid.)
var collection2 = new[] { Test.A }.Cast<int?>().ToList();
The
Castmethod can only perform boxing/unboxing conversions, reference conversions, and conversions between an enum type and its underlying integral type. The unboxing has to be to the right type though – it can’t unbox to a nullable type (unlike the C# conversion).For each value, the
Castwill unbox from the boxedenumvalue to theintvalue, and then theSelectwill convert theintvalue to anint?value.In this case you can also get away with this:
i.e. no
Caststep. However, that doesn’t work if you have anobjectarray instead:You can’t unbox a boxed enum value to a nullable int value. The
Castversion still works in that case, however, as it splits the two steps (unboxing first toint, then converting frominttoint?.)