Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

giving a class object a value c#

I have a class called playingcards it inherits from a cards class. I instantiated it as an object called chuckcards. One of the data members is CARD ID. I'm trying to assign a int to the value. it is declared public int the class. Here's how its instantiated.

playingcards[] chuckcards = new playingcards[10];

Here is how I try to assign values.

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

            chuckcards[ctr].cardID =  ctr;

            temp++;
        }

The error I get is

Object reference not set to an instance of an object.

I don't know what I'm doing wrong? Could I make a method that assigns the value to each member? if so that's gonna be a pain for certain things but I could do it? or is their a simple way?

like image 597
Yop Avatar asked Apr 24 '13 13:04

Yop


3 Answers

When you call new playingcards[10], it only creates placeholders which have the default of that type, which is null for reference types. You will have to actually new up playingcards to then use it

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

I used an object initializer to simplify the code down to one line also.

Here is what happens:

var chuckcards = new playingcards[10];

Results in the following:

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

So, you cannot do

chuckcards[0].cardID

because it is really

null.cardID

So, once you initialize the value it will have a reference from then on:

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

evaluates to

[ref to playingcards].cardID

which is valid

like image 65
Justin Pihony Avatar answered Nov 14 '22 22:11

Justin Pihony


You have defined an array of 10 slots to hold instances of playingcards, but every slot is still null
Before entering the loop you need to add an instance in every slot with

 chuckcards[0] = new  playingcards();

and so on..... (1,2,...9=max index)

eventually you could check inside the loop if you have assigned an instance to a particular slot or not

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

And remember, array index start at zero not at one

like image 24
Steve Avatar answered Nov 14 '22 21:11

Steve


You need to give chuckcards[ctr] an object instance:

chuckcards[ctr] = new playingcards();
chuckcards[ctr].cardID = ctr;
like image 4
Darren Avatar answered Nov 14 '22 21:11

Darren