Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to index for enum type in c#?

Tags:

c#

enums

indexing

Say I have the following enumerated type:

private enum ranks { ace = "Ace", two = "2", three = "3", four = "4", five = "5", six = "6", seven = "7", 
                     eight = "8", nine = "9", ten = "10", jack = "Jack", queen = "Queen", king = "King" }

ranks rank;

I know I can do things like sizeof(ranks) but is there a way to get the nth item in ranks? Say a user enters 4 and i want to set rank to the 4th enumeration without explicitly doing:

rank = ranks.four;

How can I do this?

(For the purpose of this example, assume that I MUST use enum and that I know there are other collections more suited for this problem.)

Thanks for the help. :)

like image 835
Nate Avatar asked Nov 28 '22 09:11

Nate


1 Answers

(1) Naming convention: Do not pluralise the name of an enum unless it is a set of "bit flags" that can be ored together.

(2) Always have an item in an enum which has a value of zero. Default-initialisation of enums will give it a value of zero, so it's best to have an explicit name for it (e.g. None).

(3) You can cast any value you like to an enum, provided it is the same as the underlying type of the enum (int32 by default).

So you could have an enum that looked like this:

enum Rank { None, Ace, Two, ... }

and to convert from a rank value of, say, 5 to the enum, you can just cast:

Rank rank = (Rank)5;

But you'd be better writing a method to do so that checked the range before casting, and throw an exception if it's out of range.

like image 173
Matthew Watson Avatar answered Dec 04 '22 18:12

Matthew Watson