• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 204
  • Last Modified:

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
0
cycledude
Asked:
cycledude
  • 4
  • 3
1 Solution
 
Carl TawnSystems and Integration DeveloperCommented:
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.
0
 
cycledudeAuthor Commented:
well, its the same array structure as in

string[] stuff = new string[10]

but the contents of the string are different on each iteration
0
 
Carl TawnSystems and Integration DeveloperCommented:
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

0
Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

 
cycledudeAuthor Commented:
1st one ...
0
 
Carl TawnSystems and Integration DeveloperCommented:
In that case, as I said originally, you are passing a reference to the same array to each instance, so any changes you make get made to all references.

Use the second version to create a new array for each instance and you should be ok.
0
 
cycledudeAuthor Commented:
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.
0
 
cycledudeAuthor Commented:
thanks, a little restructuring and it has worked a treat.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now