Max Max - 1 year ago 66
C# Question

Using lists of custom classes

I've recently run into a snag in my program where using a list of a user defined class has been corrupting data. Example:

class myClass {
public int x;

myList<myClass> = new List<myClass>();
myClass myObject = new myClass();


When I try to add something to the list, my data is being corrupted. I believe removing objects is also causing problems, although this could be because they're corrupted in the first place. I've seen similar issues here and there and was hoping someone could explain to me what's going on. While the links do provide me with some answers, they're not doing a good job of explaining what's going on behind the scenes.

EDIT: I should have been more clear before about how my data is being corrupted. The values in the fields of my objects are being changed when they are added to the list. For the purposes of my program, the values should all be 0 or 1 but when added to the list change to -1 to 3.

EDIT 2: The source of the problem was an unfamiliarity with C#. Coming from a C++ background I assumed that objects were passed by value and not by reference. Changing my custom class from a class to a struct resolved the issue instantly. Thanks to @MattW !

Answer Source

There isn't too much to go on here - so the following is a guess at the problem ...

Are you changing the value of myObject after adding it to the List<>? Remember that since you are adding a Class to the list (and all Classes are Reference types), that if you change the value of myObject after adding it to the list, it will be changed everywhere (including inside of your List<>).

For example:

List<myClass> myList = new List<myClass>();
myClass myObject = new myClass();
myObject.x = 5;

Console.WriteLine(myList[0].x); //this will be 5

myObject.x = 7;
Console.WriteLine(myList[0].x); //this will be 7

Even though you didn't touch the List<> itself, you changed the value of the Referenced object, so it is changed everywhere it is being Referenced.

Check Out Value vs Reference types

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download