1

I want to create enum type like:

enum Ranks{ 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace}

Is there any way to do it?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
TranceAddict
  • 187
  • 3
  • 14

3 Answers3

0

It seems there's no elegant way to do that, so here's a hack: Append an underscore at the beginning of each integer!

enum LikeThis { _1, _2, _3, _4, _5, _6 }
The SE I loved is dead
  • 1,517
  • 4
  • 23
  • 27
0

Short answer: No


Regular answer: Simply use characters and get the numeric values like this:

int numericValueOne = (int)Value.Ace;
int numericValueTwo = (int)Value.Two;

Long answer: If the end usage is for a deck of cards this is a great implementation:

public class Card
{
    private readonly Suit _suit;
    private readonly Value _value;

    public Card(int number)
    {
        _suit = (Suit)(number / 13);  // 0 = Hearts, 1 = Diamonds ...
        _value = (Value)(number % 13 + 1);  // 1 = ace, 2 = two
    }

    public Suit Suit
    {
        get { return _suit; }
    }

    public Value Value
    {
        get { return _value; }
    }

    public int ToNumber()
    {
        return (int)_suit * 13 + ((int)_value - 1);
    }
}

public enum Suit
{
    Hearts = 0,
    Diamonds = 1,
    Clubs = 2,
    Spades = 3
}

public enum Value
{
    Ace = 1,
    Two = 2,
    Three = 3,
    Four = 4,
    Five = 5,
    Six = 6,
    Seven = 7,
    Eight = 8,
    Nine = 9,
    Ten = 10,
    Jack = 11,
    Queen = 12,
    King = 13,
}

The benefit of wrapping both enums in this class is that you can use each card as a number (0-52) and/or a class. Plus you can add whatever operations, method, properties to the class as you need and when you store or transmit the data you need only use the number. Ref

Community
  • 1
  • 1
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
0

You could do something like this:

enum Ranks { Ace = 'A', Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten, King = 'K', Queen = 'Q', Jack = 'J' };

Then perform a switch on the Rank like so:

switch (Rank)
{
    case Ranks.Two:
    case Ranks.Three:
    case Ranks.Four:
        // Cast to an int and display it
        break;

    case Ranks.Ace:
    case Ranks.King:
    case Ranks.Queen:
    case Ranks.King:
        // Cast to char and display it
        break;
}

I used this in a simple blackjack game I wrote, worked well

Shadow
  • 3,926
  • 5
  • 20
  • 41