Home > Enterprise >  Create different named variables and assign classes to that variable in C#
Create different named variables and assign classes to that variable in C#

Time:02-21

Im tring to create all 52 pokercards in a loop.

Like this:

Card heart1 = new Card(1, "hearts", "hearts 1");
Card heart2 = new Card(2, "hearts", "hearts 2");

This is what I have but i'm stuck:

string[] icon = new string[]{ "hearts", "clubs", "diamonds", "spades" };
Card[] card = new Card[13];
foreach (string i in icon)
{
     for (int j = 1; j <= 13; j  )
     {

     }
}
    

I'm trying to create all 13 cards for every type of card. I want de varible to have the same name as the string with the nummber next to it.

I'm new to C# so let me know if i'm doing it wrong or if there is a better way to do this. I know I can do this by hand, but I want it to do it automatically.

CodePudding user response:

C# does not support dynamically named variables. You can declare an array of cards and initialize the elements in a loop like so:

Card[] deck = new Card[52];
string[] suits = {"hearts", "clubs", "diamonds", "spades"};
for(int i=0; i < suits.Length; i  )
{
    for (int j = 1; j <= deck.Length/suits.Length; j  )
    {
        deck[i*j] = new Card(j, suits[i], $"{i} of {suits[i]}");
    }
}
  • Related