I have an interesting problem. I have a Class Person:
public class Person
{
public string Name { get; set; }
public int? Score { get; set; }
public int NbrOfWins { get; set; }
public int NbrOfLosses { get; set; }
public int HighScore { get; set; }
}
I create an Observable collection:
ObservableCollection<Person> test = new ObservableCollection<Person>();
I have an extension method to add to the observable collection:
public static void myFillTest<T>(this ObservableCollection<T> value1, T value2, int nbr)
{
for (int x = 0; x < nbr; x++)
{
value1.Add(value2);
}
}
I add 5 items to the collection like this:
test.myFillTest(new Person { Name = "None" }, 5);
If I change the name in one instance:
test[2].Name = "John";
All of the items in the collection change, as if they were all pointing to the same thing. Any reason why this would be? By the way, this works for T of type int, and string, but not for a typeof class.
This is because the class Person is a reference type while the integer is value type. When you add the same int 5 times, it is copied, when you add person 5 times, its one instance added to 5 different indexes. You can read about reference types here http://msdn.microsoft.com/en-us/library/490f96s2.aspx . You need to copy your object of type person if you want it to work as expected.
You can change your code to the following in order to always create new objects:
public static void MyFillTest<T>(this ObservableCollection<T> value1, T value2, int nbr)
{
for (int x = 0; x < nbr; x++)
{
if (typeof(T).IsValueType)
{
value1.Add(value2);
}
else
{
if (value2 is ICloneable)
{
ICloneable cloneable = (ICloneable)value2;
value1.Add((T)cloneable.Clone());
}
}
}
}
public class Person : ICloneable
{
public string Name { get; set; }
public int? Score { get; set; }
public int NbrOfWins { get; set; }
public int NbrOfLosses { get; set; }
public int HighScore { get; set; }
#region ICloneable Members
public object Clone()
{
return new Person
{
Name = this.Name,
Score = this.Score,
NbrOfWins = this.NbrOfWins,
NbrOfLosses = this.NbrOfLosses,
HighScore = this.HighScore
};
}
#endregion
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With