Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

Try the following code

public enum Color
{
    Blue=1,
    Red=2, 
    Green=3 
}

public List<Color> ConvertColorEnum()
{
    var intColor = new List<int>(){1,2,3};
    return intColor.Cast<Color>().ToList();
}

Do you think the ConvertColorEnum() will return a list of color, i.e., List<Color>(){Color.Blue, Color.Red, Color.Green}?

I tested this on 2 machines, one with .net 3.5 ( mscorlib version 2.0.50727.1433), another with .net 3.5 SP1 ( mscorlib version 2.0.50727.3082). The results were different-- the .net 3.5 threw an InvalidCastException because couldn't convert integer to enum, whereas .net 3.5 SP1 could run successfully, with correct results returned.

Anyone would like to try this on his/her machine and report the result or explain why this is so?

like image 738
Graviton Avatar asked May 14 '09 13:05

Graviton


People also ask

Can you cast an int to an enum?

You can explicitly type cast an int to a particular enum type, as shown below.

Can you cast an enum?

Enum's in . Net are integral types and therefore any valid integral value can be cast to an Enum type. This is still possible even when the value being cast is outside of the values defined for the given enumeration!

How do you convert a string value to a specific enum type in C#?

TryParse() method converts the string representation of enum member name or numeric value to an equivalent enum object. The Enum. TryParse() method returns a boolean to indicate whether the specified string is converted to enum or not. Returns true if the conversion succeeded; otherwise, returns false .


1 Answers

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

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

As for the why...?

like image 143
Marc Gravell Avatar answered Sep 24 '22 05:09

Marc Gravell