So I recently wrote an algorithm which I posted on stack exchange/code review and it was very well received and I got loads of improvements suggested. I’m new to C# and I don’t really understand the IEnumerable interface.
How do I print to the console my entire deck?
The code below is a method, if I call the method there is nothing else I can do… Or can I?
One of the Methods I was suggested to use is:
public IEnumerable<Card> CreateDeck()
{
var deck = new List<Card>();
foreach(var value in Enum.GetValues<CardValue>())
foreach (var suit in Enum.GetValues<CardSuit>())
deck.Add(new Card(value, suit));
return deck;
}
My Enums for Cards
public enum CardValue {Ace, King, Queen, Jack, Ten, Nine, Eight, Seven, Six, Five, Four, Three, Two};
public enum CardSuit {Spades, Clubs, Hearts, Diamonds};
Creating a Card
public struct Card
{
public CardValue Value { get; }
public CardSuit Suit { get; }
public Card(CardValue value, CardSuit suit)
{
Value = value;
Suit = suit;
}
public override string ToString()
{
return $"{Value} of {Suit}";
}
}
>Solution :
Just use a simple foreach loop:
foreach (var card in CreateDeck()) Console.WriteLine(card);
This uses the Console.WriteLine(object) overload, that will internally call the ToString() method defined on Card.
As an aside, you could reduce memory usage in your CreateDeck method by using yield return instead of allocating a list:
public IEnumerable<Card> CreateDeck()
{
foreach (var value in Enum.GetValues<CardValue>())
{
foreach (var suit in Enum.GetValues<CardSuit>())
{
yield return new Card(value, suit);
}
}
}
This way, Cards are created on-demand as you iterate, and immediately become eligible for garbage collection after they leave scope.
If you find that you need a list, you can always do this:
var cards = CreateDeck().ToList();