It happens because the class, in your case,
, 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:
SampleData type a
- 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