Nate
Nate

Reputation: 6454

Equivalent to index for enum type in c#?

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. :)

Upvotes: 4

Views: 13033

Answers (7)

Niranjan Singh
Niranjan Singh

Reputation: 18290

You can specify integer value in your enum that will help you to get your custom value to identify their position.

Check this:

 void Main()
{
    int rank = (int)ranks.two;
    Console.WriteLine(rank);
    ranks rankEnum = (ranks)2;
    Console.WriteLine(rankEnum.ToString());

}
private enum ranks 
    { ace = 1, two = 2, three = 3, four = 4, five = 5, six = 6, seven = 7, 
                     eight = 8, nine = 9, ten = 10 }

//Output

2
two

You can get the index of the enum as:

int position = EnumUtil.GetEnumIndex<ranks>(ranks.four);

//
public static class EnumUtil
    {        
            public static int GetEnumIndex<T>(T value)
            {
                int index = -1;
                int itemIndex = 0;
                foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
                {
                    if (item.Equals(value))
                    {
                        index = itemIndex + 1;
                        break;
                    }
                    itemIndex ++;
                }
                return index;
            }
    }

Hope this help

Upvotes: 2

Shelest
Shelest

Reputation: 670

Basicly Enumerations are used to provide some standart that tell everyone what exsacly values could be used. But if enum values must to care some information except this "standart" - using enums is not good practice.

Considering your case "rank = ranks.four;"i woul prefer to use Class with constant string fields instead of Enum.

Upvotes: 0

RJ Lohan
RJ Lohan

Reputation: 6527

As noted, your enum declaration is invalid, but perhaps what you want to do is something more like;

private enum Ranks
{
    Ace = 1,
    Two = 2,
    Three = 3,
    . . .
    Jack = 11,
    Queen = 12,
    King = 13
}


public void SomeMethod()
{ 
    Ranks rank = Ranks.Jack;
    int rankValue = (int)rank;
    string rankName = rank.ToString();
}

public Ranks GetRank(int i)
{
    string name = Enum.GetName(typeof (Ranks), i);
    if (null == name) throw new Exception();
    return (Ranks)Enum.Parse(typeof (Ranks), name);
}

Upvotes: 7

Matthew Watson
Matthew Watson

Reputation: 109567

(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.

Upvotes: 8

Guffa
Guffa

Reputation: 700362

The enum values have to be numeric, but you can add a description to them:

private enum ranks {
  [Description("Ace")] ace = 1,
  two = 2,
  three = 3,
  four = 4,
  five = 5,
  six = 6,
  seven = 7,
  eight = 8,
  nine = 9,
  ten = 10,
  [Description("Jack")] jack = 11,
  [Description("Queen")] queen = 12,
  [Description("King")] king = 13
}

Now you can cast any integer value to an enum value:

 (ranks)4

You can use this function to get the description or the rank:

private static string GetRankName(ranks rank) {
  FieldInfo fi = typeof(ranks).GetField(rank.ToString());
  DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
  if (attributes.Length > 0) {
    return attributes[0].Description;
  } else {
    return ((int)rank).ToString();
  }
}

Usage:

Console.WriteLine(GetRankName((ranks)4));

Upvotes: 1

Martin Ernst
Martin Ernst

Reputation: 5679

If your enum values don't run sequentially from 0 to X in increments of 1, then you can also do the following:

var rank = (rank)Enum.GetValues(typeof(rank))[3];

Upvotes: 2

YavgenyP
YavgenyP

Reputation: 2123

Im not sure what you're trying to do, but what u posted is NOT a legal enum in the world of c#.
if you have a following sample enum:

  enum sample
    {
        ace = 1,
        two = 2,
        three = 3
    }

then you can always cast any int to this enum (assuming you are sure the value is valid):

  int i = 3;
  sample mySample = (sample)i;

Upvotes: 4

Related Questions