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?
You can explicitly type cast an int to a particular enum type, as shown below.
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!
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 .
If you want it to work either way, use Select
instead.
return intColor.Select(i=>(Color)i).ToList();
As for the why...?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With