Getting Enum Type from Value
-
Alright, I have an enum called Suit ...
public enum Suit { Hearts = 0, Diamonds = 1, Spades = 2, Clubs = 3, Null = -1, }
And I have a function I need to create that will return the correct rank type given an integer. I have written this function to work with a switch statement: switch(i) { case 0: return hearts; ... } BUT, there must be a much cleaner way to do this, by parsing the enum type from the value - I just don't know the syntax and can't seem to find it. It must be something like: Rank r = Enum.Parse(Rank, i); ... of course that doens't work. But it must be something similar. Any suggestions? -
Alright, I have an enum called Suit ...
public enum Suit { Hearts = 0, Diamonds = 1, Spades = 2, Clubs = 3, Null = -1, }
And I have a function I need to create that will return the correct rank type given an integer. I have written this function to work with a switch statement: switch(i) { case 0: return hearts; ... } BUT, there must be a much cleaner way to do this, by parsing the enum type from the value - I just don't know the syntax and can't seem to find it. It must be something like: Rank r = Enum.Parse(Rank, i); ... of course that doens't work. But it must be something similar. Any suggestions?Its easier than you would expect. Just convert the type: int i = 0; Suit suit = (Suit)i; // suit == Suit.Hearts int index = (int)suit; // index == 0;
-
Alright, I have an enum called Suit ...
public enum Suit { Hearts = 0, Diamonds = 1, Spades = 2, Clubs = 3, Null = -1, }
And I have a function I need to create that will return the correct rank type given an integer. I have written this function to work with a switch statement: switch(i) { case 0: return hearts; ... } BUT, there must be a much cleaner way to do this, by parsing the enum type from the value - I just don't know the syntax and can't seem to find it. It must be something like: Rank r = Enum.Parse(Rank, i); ... of course that doens't work. But it must be something similar. Any suggestions?Simply casting to the enum type should work.
Rank r = (Rank)i;
Need to be careful though, this will compile and run even if the value of i is outside the range of Rank. Regards Senthil _____________________________ My Blog | My Articles | WinMacro
-
Simply casting to the enum type should work.
Rank r = (Rank)i;
Need to be careful though, this will compile and run even if the value of i is outside the range of Rank. Regards Senthil _____________________________ My Blog | My Articles | WinMacro
Thanks! Works perfect! I followed your advice and added error checking to make sure the value is between 0 and NUMRANKS (and 0 AND NUMSUITS for suits). Thanks again!