Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int to enum value? [duplicate]

Tags:

c#

class

Here's my code thats throwing an error saying Cannot convert type "int" to Cards.Suits and Cannot convert type "int" to Cards.Rank

private Card[] cards;
public Deck()
{
    cards = new Card[52];
    for (int suitVal = 0; suitVal < 4; suitVal++)
    {
        for (int rankVal = 0; rankVal < 14; rankVal++)
        {
            cards[suitVal * 13 + rankVal - 1] = new Card((Suits)suitVal, (Rank)rankVal);
        }
     }
}

the cards constructor is

public readonly Suits suit;
public readonly Rank rank;
public Card(Suits newSuit, Rank newRank)
{
    suit = newSuit;
    rank = newRank;
}

Now the Suits enum and Rank enum are as a regular deck of cards starting at ACE = 1 so on and suits are DIAMONDS, CLUBS, HEARTS, SPADES. Can anyone tell me why im getting the above error. The following code was taking from a book. Thanks!

*EDIT

    public enum ranks
    {
        ACE = 1,
        TWO,
        THREE,
        FOUR,
        FIVE,
        SIX,
        SEVEN,
        EIGHT,
        NINE,
        TEN,
        JACK,
        QUEEN,
        KING,
    }

    public enum Suit
    {
        DIAMOND,
        CLUB,
        HEART,
        SPADE,
    }
like image 803
MikaAK Avatar asked Aug 02 '13 05:08

MikaAK


2 Answers

According to your enum declarations, Suit is in the [0..3] range, while ranks is in the [1..13] range (pay attention, that ranks is not zero based), so the inner for loop should be corrected:

  for (int rankVal = 0; rankVal < 13; rankVal++) // <- 14 changed for 13: [0..13] has the same length as [1..14] 
  { 
    cards[suitVal * 13 + rankVal] = new Card((Suits)suitVal, (Rank)(rankVal + 1)); // <- removed -1 from index; add 1 to rankVal, we need [1..14], not [0..13]
    ...
like image 66
Dmitry Bychenko Avatar answered Oct 02 '22 13:10

Dmitry Bychenko


change your line in for like this

 cards[suitVal * 13 + rankVal] = new Card(((Suit)suitVal), ((ranks)rankVal));

and as your class is taking enums in constructor so change it like this

public readonly Suit suit;
public readonly ranks rank;
public Card(Suit newSuit, ranks newRank)
{
    suit = newSuit;
    rank = newRank;
}
like image 38
Ehsan Avatar answered Oct 02 '22 13:10

Ehsan