Posts: 272
Threads: 21
Thanks Received:
0 in 0 posts
Thanks Given: 0
Joined: Jun 2012
Reputation:
0
hello, i am coding a program but i have a problem with it.
i have defined a list of items and a item of the same class of the list to read a item and add it to list. i read it and i add it to list. first time is everything ok but if i read it more times, first item i add is the same as second. i mean if for example first item is value 1 and second is value 3, when i read first time item value of list is 1 but second time, both elements of the list are 3.
i dont know why this can be happen.
Could anyone help me please?
Posts: 768
Threads: 40
Thanks Received:
0 in 0 posts
Thanks Given: 0
Joined: May 2011
Reputation:
0
U are trying to add the same class and just changed some values.
The values inside a class are passed by reference.
So lets say your class named Items. And u do this.
Items itemA = new Items();
itemA.id = 1;
Items itemB = itemA;
itemB.id = 2;
U would think that itemB is a copy of itemA with only a different id.
But its not. itemB is a reference to itemA. So everything u change in itemB gets changed in itemA aswell.
If u really want to make a copy lookup MemberwiseClone()
Posts: 272
Threads: 21
Thanks Received:
0 in 0 posts
Thanks Given: 0
Joined: Jun 2012
Reputation:
0
U are trying to add the same class and just changed some values.
The values inside a class are passed by reference.
So lets say your class named Items. And u do this.
Items itemA = new Items();
itemA.id = 1;
Items itemB = itemA;
itemB.id = 2;
U would think that itemB is a copy of itemA with only a different id.
But its not. itemB is a reference to itemA. So everything u change in itemB gets changed in itemA aswell.
If u really want to make a copy lookup MemberwiseClone()
i think i havent explain my problem well.
i have this:
List<Items> itemA = new List<Items>();
Items itemB;
and i want to add elements to list so i do this:
for(int i = 0; i < 5; i++)
{
itemB.ID = br.readInt32();
itemB.power = br.readInt32();
ItemA.Add(itemB);
}
and the result should be these:
itemA[0].ID = 1
ItemA[0].power = 1
itemA[1].ID = 2
ItemA[1].power = 2
itemA[2].ID = 3
ItemA[2].power = 3
itemA[3].ID = 4
ItemA[3].power = 4
itemA[4].ID = 5
ItemA[4].power = 5
but instead of this, the results are these:
itemA[0].ID = 5
ItemA[0].power = 5
itemA[1].ID = 5
ItemA[1].power = 5
itemA[2].ID = 5
ItemA[2].power = 5
itemA[3].ID = 5
ItemA[3].power = 5
itemA[4].ID = 5
ItemA[4].power = 5
and i dunno why this happen
Posts: 768
Threads: 40
Thanks Received:
0 in 0 posts
Thanks Given: 0
Joined: May 2011
Reputation:
0
Try this
for(int i = 0; i
{
itemB = new Items();
itemB.ID = br.readInt32();
itemB.power = br.readInt32();
ItemA.Add(itemB);
}
The reason why it was happening is because of the reference.
itemB stays the same when u dont initialize it again.
And even if added to the list, itemB is still itemB.
So basically u just added 5x the same object to the list that all point to the same data.