I have implemented the following code and when I want to update(add or remove) from the ColumnsList of one of the instances, it affectss all the other instances.
public class XMLAttributeStructure
{
public string TableName { get; set; }
public int Row { get; set; }
public List<string> ColumnsList { get; set; }
public string Attribute { get; set; }
public string Value { get; set; }
public XMLAttributeStructure(string tablename, int row, List<string> columnlist, string attribute, string value)
{
TableName = tablename;
Row = row;
ColumnsList = columnlist;
Attribute = attribute;
Value = value;
}
}
output :
For example think I already have 2 objects with columnsList which contains "No", "Status". And think I removed "ST" from the first instance's columnList using the following.
selectedObj.ColumnsList.Remove("ST");
selectedObj is the first instance. But "ST" in the second object also gets removed.
Disregarding any other problem, the simplest solution would be to just reallocate your list
public XMLAttributeStructure(string tablename, int row, List<string> columnlist, string attribute, string value)
{
...
ColumnsList = columnlist.ToList();
Another solution would be to do this when you call the constructor. That way the constructor isn't doing anything unexpected, and it lets the caller choose if they want the class to have a new instance or not
XMLAttributes.Add(
new XMLAttributeStructure(
tableName,
i,
colList.ToList(),
attribute,
value));
The longer story, is when you copy a reference type, you aren't making a copy of the actual object (clone), you are making a copy of the reference to the object
Additional Resources