C# Create a deck of Cards using foreach

c#, enums, foreach, struct

Solution

You need to create a list; right now your `NewDeck()` method doesn't define one.

public static List<Card> NewDeck() {
    List<Card> deck = new List<Card>();
    foreach (Cards.Rank r in Enum.GetValues(typeof(Rank))) {
        foreach (Cards.Suit s in Enum.GetValues(typeof(Suit))) {
            deck.Add(new Card(s, r));
        }
    }

    return deck;
}

Problem

This is a homework assignment FYI. And thanks for at least looking at this. So we're learning about `enums`, `List<>`, `IComparable<T>` and `structs`, and we're creating a deck of cards. I have a Card Struct, that says to create a card, it needs a rank and suit. I have enums for both. I'm having trouble with the NewDeck() method. We were given the method header to use, and given a TIP to "use the static method GetValues to loop through all Rank Enumerators". We were also given the foreach loop. We're not supposed to call a sort, because looping through all the ranks should create a list already sorted. I'm having trouble knowing how to add Cards to the deck. To add the Card, I would think I might use Card.Add, but it's not showing up in code completion, and it's not an option, and I'm not sure why. Here's the code for my Cards Struct- ``` namespace Cards { struct Card : IComparable<Card> { public Suit Suit { get; private set; } public Rank Rank { get; private set; } public Card(Suit suit, Rank rank) : this() { this.Suit = suit; this.Rank = rank; } public override string ToString() { return string.Format("{0} {1}", (Char)this.Suit, this.Rank); } public int CompareTo(Card other) { return Rank.CompareTo(other.Rank); } } public enum Suit { Spades = 9824, Clubs = 9827, Diamonds = 9830, Hearts = 9829 } public enum Rank { Ace, Deuce, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King }; } ``` And here's the code for my newDeckMethod() ``` public static List<Card> NewDeck() { foreach (Cards.Rank r in Enum.GetValues(typeof(Rank))) //Card.Add } ```

Original source