Reputation: 3
I have the following class in Wpf
public class test
{
public int id;
public string name;
}
As well as two of the list of ObservableCollection types that I've made right
private ObservableCollection<Test> ClassTest;
private ObservableCollection<Test> TempClassTest;
public MainWindow()
{
InitializeComponent();
ClassTest = new ObservableCollection<Test>();
TempClassTest = new ObservableCollection<Test>();
ClassTest.Add(new Test() { id = 1, name = "T1" });
ClassTest.Add(new Test() { id = 2, name = "T2" });
ClassTest.Add(new Test() { id = 3, name = "T3" });
}
The problem is that whenever the test method is changed, it changes in the first variable like the following code:
private void Button_Click(object sender, RoutedEventArgs e)
{
TempClassTest = ClassTest;
TempClassTest[0].id = 1110;
}
Now the value of ClassTest[0] is id=1110
Upvotes: 0
Views: 475
Reputation: 1937
In C# - Read about reference types. System.Collections.ObjectModel.ObservableCollection is a reference type. Following line of code:
TempClassTest = ClassTest;
Creates a shallow copy (it does not create entirly new member wise list).
The item in the Collection is also a ReferenceType, so you need to Deep Clone the item again.
Do something like:
public class Test: ICloneable
{
public int Id { get; set; }
public string Name { get; set; }
public object Clone()
{
return new Sample { Id = this.Id, Name = this.Name };
}
}
And then,
ObservableCollection<Test> coll1 = new ObservableCollection<Test>();
coll1.Add(new Test{ Id = 1 });
coll1.Add(new Test{ Id = 2 });
coll1.Add(new Test{ Id = 3 });
ObservableCollection<Test> coll2 = new ObservableCollection<Test>();
foreach (var item in coll1)
{
coll2.Add(item.Clone() as Test);
}
coll2[0].Id = 1500;
Upvotes: 1
Reputation: 607
the first variable object is assigned to second variable. so, the first variable and second variable pointing the same memory address. so, you change any value of first or second it should effect on two variables.
You use clone
Upvotes: 0