Link to home
Start Free TrialLog in
Avatar of cycledude
cycledudeFlag for United Kingdom of Great Britain and Northern Ireland

asked on

c# 2010 winforms list of classes problem

Hi

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;


}

}

Open in new window


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));

Open in new window


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
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

You mean you are passing the same instance of "stuff" to each MyClass object? What you are actually passing is a pointer to the array, not a copy.

You should look at creating a copy of the array inside each MyClass instance if you want them to remain separate.
Avatar of cycledude

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
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:
string[] stuff = new string[10];

for ( ... )
{
    stuff[0] = "something";
    stuff[1] = "something else";
    ...
}

Open in new window

Or are you doing:
string[] stuff;

for ( ... )
{
    stuff = new string[10];
    stuff[0] = "something";
    stuff[1] = "something else";
    ...
}

Open in new window

1st one ...
ASKER CERTIFIED SOLUTION
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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, a little restructuring and it has worked a treat.