Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If your <code>Student</code> 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 <code>Student</code> instances. By copying your list you simply duplicated your references but not the instances. What you have after the copy is something like this:</p> <pre><code>List 1 List 2 instance S1 ref to S1 ref to S1 Name: Akash ref to S2 ref to S2 ... ... ... </code></pre> <p>So if you do something like <code>list1[0].Name = "Jim"</code>, you'll update the instance <code>S1</code> and you'll see the change in both lists, since both lists refer to the same set of instances.</p> <p>What you need to do is create a clone of not only the list in this case but all the objects <em>inside</em> the list - you need to clone all your <code>Student</code> objects as well. This is called a deep copy. Something like this:</p> <pre><code>class StudentList : List&lt;Student&gt;, ICloneable { public object Clone () { StudentList oNewList = new StudentList (); for ( int i = 0; i &lt; Count; i++ ) { oNewList.Add ( this[i].Clone () as Student ); } return ( oNewList ); } } </code></pre> <p>You call this like so:</p> <pre><code>StudentList oClonedList = lstStudent.Clone () as StudentList; </code></pre> <p>You also need to make your <code>Student</code> class cloneable by implementing the <a href="http://msdn.microsoft.com/en-us/library/system.icloneable.aspx" rel="nofollow"><code>ICloneable</code></a> interface.</p> <p>Don't forget, though, that after this, you'll have 2 separate lists with 2 independent sets of <code>Student</code> objects - modifying one <code>Student</code>instance will have no effect on students in your other list.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload