Unable ( or able) to List<int>.Cast<Enum>()?

If you want it to work either way, use Select instead.

return intColor.Select(i=>(Color)i).ToList();

As for the why...?


The Cast extension method makes use of an iterator which, on move next, stores the output of the original enumerator in an object variable (so boxing as needed) then attempts to cast that to the result type.

Value types in boxed form do not respond to the cast operation in the same way they would if they were unboxed (where various automatic conversions are possible) instead they only allow casting to their original unboxed form.

I would imagine that the previous implementation of the Cast extension was either doing it completely differently or had some special casing for enum types to convert to an integral form (this is tricky as you must deal with all possible forms)

Marc's answer as to the correct solution is completely correct and is actually more efficient than the cast anyway for the aforementioned boxing reasons.


You can read about the difference between the SP1 and the original release of the .net 3.5 framework in the release notes.

Here's what it says for this particular issue:

In LINQ query expressions over non-generic collections such as System.Collections.ArrayList, the from clause of the query is rewritten by the compiler to include a call to the Cast operator. Cast converts all element types to the type specified in the from clause in the query. In addition, in the original release version of Visual C# 2008, the Cast operator also performs some value type conversions and user-defined conversions. However, these conversions are performed by using the System.Convert class instead of the standard C# semantics. These conversions also cause significant performance issues in certain scenarios. In Visual C# 2008 SP1, the Cast operator is modified to throw an InvalidCastException for numeric value type and user-defined conversions. This change eliminates both the non-standard C# cast semantics and the performance issue. This change is illustrated in the following example.

You can also get more details in this blog post.

Tags:

C#