Giving the class object a C # value

I have a class called games that it inherits from the map class. I created it as an object called chuckcards. One of the data elements is the CARD identifier. I am trying to assign an int value. he is declared open in the classroom. Here's a copy of it.

playingcards[] chuckcards = new playingcards[10];

This is how I try to assign values.

for (int ctr = 1; ctr < 10; ctr++)
        {

            chuckcards[ctr].cardID =  ctr;

            temp++;
        }

The error I get is

The reference to the object is not set to the instance of the object.

I don’t know what am I doing wrong? Can I create a method that assigns a value to each member? if it hurts for certain things, but can I do it? or is it their easy way?

+5
source share
5 answers

new playingcards[10], , , null . ,

    for (int ctr = 1; ctr < 10; ctr++)
    {
        chuckcards[ctr] = new playcards{cardID=ctr};
        temp++;
    }

, .

:

var chuckcards = new playingcards[10];

:

chuckcards[0] = null
...
chuckcards[9] = null

,

chuckcards[0].cardID

null.cardID

, , :

chuckcards[0] = new playingcards();
chuckcards[0].cardID = ctr;

[ref to playingcards].cardID

+7

10 , - .

 chuckcards[0] = new  playingcards();

....... (1,2,... 9 = )

,

 for (int ctr = 0; ctr < 10; ctr++)
 {
    if(chuckcards[i] != null)
    {
        chuckcards[ctr].cardID =  ctr;
        temp++;
    }
 }

,

+5

chuckcards[ctr] :

chuckcards[ctr] = new playingcards();
chuckcards[ctr].cardID = ctr;
+4

chuckcards [ctr] is null, you need to instantiate it

playingcards[] chuckcards = new playingcards[10];

for (int ctr = 0; ctr < 10; ctr++)
{
   chuckcards[ctr] = new playingcards();
   chuckcards[ctr].cardID =  ctr;
}
+3
source

Chuckards [ctr] are null. You need to control it.

for (int ctr = 1; ctr < 10; ctr++)
{
    chuckcards[ctr] = new playingcards();
    chuckcards[ctr].cardID =  ctr;
    temp++;
}

To have less code, you can create another constructor that needs an identifier. Then you have:

for (int ctr = 1; ctr < 10; ctr++)
{
    chuckcards[ctr] = new playingcards(ctr);
    temp++;
}
+2
source

All Articles