0

I have the following piece of code :

private List<KeyValuePair<int, string>> _list = new List<KeyValuePair<int, string>>();

public MyclassConstructor()
{
    foreach (Enum value in Enum.GetValues(typeof(FontStyle)))
        _list.Add(new KeyValuePair<int, string>((int)value, value.ToString()));
}

I can't figure out how to get the int part of this enum as the key... pretty dumb question I'm sure but I can't get it working.

I was refering to this article up here on stackoverflow but as you can see this doesn't work

So how can I get the int value of the enum?

Edit : When I try to compile I got the following error message "Cannot convert type 'System.Enum' to 'int'"

Community
  • 1
  • 1
Rémi
  • 3,406
  • 5
  • 23
  • 43
  • Sorry, it isn't clear: *what* isn't working in the code above? Also, could you make the KeyValuePair's key type `FontStyle` instead of `int`? – Dan J Jun 25 '13 at 17:34
  • Casting the value as an int should take care of it. Surprised that isn't working. – Bill Gregg Jun 25 '13 at 17:35
  • @DanJ Sorry, it simply doesn't compile with the error message "Cannot convert type 'System.Enum' to 'int'". I will edit the question – Rémi Jun 25 '13 at 17:36

3 Answers3

4

You should change your loop statement to loop over FontStyle, not Enum:

foreach (FontStyle value in Enum.GetValues(typeof(FontStyle)))

Or using implicit typed variable and var keyword:

foreach (var value in Enum.GetValues(typeof(FontStyle)))
MarcinJuraszek
  • 118,129
  • 14
  • 170
  • 241
  • This was it... Just fix typo `FontStylevalue` to `FontStyle value` and I will mark as answer as soon as I will be able to do so – Rémi Jun 25 '13 at 17:39
0

If you want to get the Enum Name from value?yes means, just call Enum.GetName(typeof(yourtype),value).Try to use var Keyword.

Ravuthasamy
  • 549
  • 1
  • 6
  • 15
0

This will work:

var _list = Enum.GetValues(typeof(FontStyle))
            .Cast<FontStyle>()
            .Select(x => new KeyValuePair<int, string>((int)x, x.ToString()));
Vlad Bezden
  • 59,971
  • 18
  • 206
  • 157