It happens because the class, in your case,
SampleData
, is a
reference type. When you copy an instance of such type, you actually obtain a second reference referencing the
same object. This way, you reference the same set of objects in two different lists. If you modify one referenced object property (or any other instance member) throw its reference, the other reference (in this case, in the second list), also referenced the same object, a modified one.
If you need the lists to be truly independent, do one of the following:
- Make
SampleData
type a struct
, not class
. - Keep it a class, but clone elements of this class instead of copying it (that is, instead of copying just the reference). This class is so simple that you can simply use shallow cloning, which is done via the method
System.Object.MemberwiseClone
:
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx[^].
See also:
http://msdn.microsoft.com/en-us/library/t63sy5hs%28v=vs.110%29.aspx[
^],
http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy[
^],
http://en.wikipedia.org/wiki/Deep_copy#Deep_copy[
^].
—SA