If your Student
type is a class (reference type), a list will only contain references to those instances. This means that when you make a copy of your list, the copied list will also have only references that still point to the same Student
instances. By copying your list you simply duplicated your references but not the instances. What you have after the copy is something like this:
List 1 List 2 instance S1
ref to S1 ref to S1 Name: Akash
ref to S2 ref to S2 ...
... ...
So if you do something like list1[0].Name = "Jim"
, you'll update the instance S1
and you'll see the change in both lists, since both lists refer to the same set of instances.
What you need to do is create a clone of not only the list in this case but all the objects inside the list - you need to clone all your Student
objects as well. This is called a deep copy. Something like this:
class StudentList : List<Student>, ICloneable
{
public object Clone ()
{
StudentList oNewList = new StudentList ();
for ( int i = 0; i < Count; i++ )
{
oNewList.Add ( this[i].Clone () as Student );
}
return ( oNewList );
}
}
You call this like so:
StudentList oClonedList = lstStudent.Clone () as StudentList;
You also need to make your Student
class cloneable by implementing the ICloneable
interface.
Don't forget, though, that after this, you'll have 2 separate lists with 2 independent sets of Student
objects - modifying one Student
instance will have no effect on students in your other list.