Avatar of mycomputerfund
mycomputerfund

asked on 

Problem instantiating an array of objects

I try to loop through an array of objects, and set values to each property but get an NullReferenceException error in the loop itself.  Im not sure how the objects are null since im using the new keyword when defining the object array.
class Card
{
        public int Value = 0;
        public int Suit = 0;
        public string Name = "";
}
 
....
 
private void setCards() 
        {
            Card[] cardSpades = new Card[13];
            Card[] cardHearts = new Card[13];
 
            for (int i = 0; i < 13; i++)
            {
                cardSpades[i].Suit = 0; <--null error
                cardSpades[i].Value = i;
                cardHearts[i].Suit = 2;
                cardHearts[i].Value = i;
            }
       }

Open in new window

.NET ProgrammingEditors IDEs

Avatar of undefined
Last Comment
mycomputerfund

8/22/2022 - Mon