How do I copy (and insert) the last object in a list.
public class MyObject
{
public string first {get;set;}
public string second {get;set;}
}
List<MyObject> list = new List<MyObject>();
list.Add(new MyObject{first = "one", second = "two"});
list.Add(new MyObject{first = "here", second = "there"});
list.Add(new MyObject{first = "car", second = "plane"});
MyObject newObj = new MyObject();
list.Add(newObj);
It seems as if the last two objects in the list is references to the same object. How do I create a new object that is still a copy of the last object in the list?
EDIT
I shouldn’t have simplified my problem and the class (not actually called MyObject) for this example. It’s actually much larger with more children objects and lists.
There are two common ways:
(1) Write a Copy Constructor for the MyObject class, and use it to make a copy of the object, then insert the copy.
(2) Or write a Clone method for the MyObject class, and use that to make a copy, then insert the copy.
However, in the code you presented, you are NOT making a copy of anything, nor are you inserting into the list a reference to an existing object.
Here’s an example how you can do it: