cycledude
asked on
c# 2010 winforms list of classes problem
Hi
I have a class, like this:
simple enough...
I have a list of this class, which I am adding to like so
this is fine when I add the first entry, but for subsequent entries, the 'stuff' array is being applied to ALL entries in the list, not just the new one.
I am baffled as to why, I am sure someone can enlighten me.
cheers
CD
I have a class, like this:
class MyClass
{
public int ID {get; set;}
public string[] Stuff = new string[10];
public MyClass(int ID, string[] Stuff)
{
this.ID = ID;
this.Stuff = Stuff;
}
}
simple enough...
I have a list of this class, which I am adding to like so
List<MyClass> myStuff = new List<MyClass>();
myStuff.add(new MyClass(id,stuff));
this is fine when I add the first entry, but for subsequent entries, the 'stuff' array is being applied to ALL entries in the list, not just the new one.
I am baffled as to why, I am sure someone can enlighten me.
cheers
CD
ASKER
well, its the same array structure as in
string[] stuff = new string[10]
but the contents of the string are different on each iteration
string[] stuff = new string[10]
but the contents of the string are different on each iteration
But are you overwriting the contents of the array in each iteration, or are you reinitializing the array each time.
i.e. Are you doing:
i.e. Are you doing:
string[] stuff = new string[10];
for ( ... )
{
stuff[0] = "something";
stuff[1] = "something else";
...
}
Or are you doing:string[] stuff;
for ( ... )
{
stuff = new string[10];
stuff[0] = "something";
stuff[1] = "something else";
...
}
ASKER
1st one ...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Hi
thanks, I will try to re-structure the code so that I can re-initialise the array on each iteration...
will let you know how i get on.
thanks, I will try to re-structure the code so that I can re-initialise the array on each iteration...
will let you know how i get on.
ASKER
thanks, a little restructuring and it has worked a treat.
You should look at creating a copy of the array inside each MyClass instance if you want them to remain separate.