I am new to C#, so bear with me. I have a problem in c# where I can't decide on whether I need a class or a struct. I'm creating a List of either the class or struct and adding elements to it. If I use a struct, then I can add an item, alter it, and add it again and the changes will be seen because it is passed by value. The problem is, structs are not mutable so I can't edit any of the elements later. If I use a class, then if I add an item and alter it, all the items in the list get changed. I have to create a new instance of the object each time if I want it to be different. But I have an object that I only want to change one item in, so I have to copy all the other items to the new object?! WHY? Is there a better solution?
This code illustrates my problem:
namespace TestError
{
public partial class Form1 : Form
{
private List<Thing> lst;
private Thing obj;
public Form1()
{
InitializeComponent();
lst = new List<Thing>();
obj = new Thing();
obj.a = "bla";
lst.Add(obj);
//obj = new Thing();
obj.a = "thing";
lst.Add(obj);
foreach (Thing t in lst)
listBox1.Items.Add(t.a);
}
}
class Thing
{
public string a;
//problem is there are many more items here that don't change!
}
}
Why the struct doesn't work:
namespace TestError
{
public partial class Form1 : Form
{
private List<Thing> lst;
private Thing obj;
public Form1()
{
InitializeComponent();
lst = new List<Thing>();
obj = new Thing();
obj.a = "bla";
lst.Add(obj);
lst[0].a = "new"; //error. if i change it to class, it works.
obj.a = "thing";
lst.Add(obj);
foreach (Thing t in lst)
listBox1.Items.Add(t.a);
}
}
struct Thing
{
public string a;
}
}