C# cloning objects and lists
Okay I had a situation where I needed to make a copy of my generic list (as a temporary backup). What I did was in my class I added a method ‘Clone’.
public object Clone()
{
var ms = new MemoryStream();
var bf = new BinaryFormatter();bf.Serialize(ms, this);
ms.Position = 0;var obj = bf.Deserialize(ms);
ms.Close();return obj;
}
With this I could clone each object in my generic list by doing it in a foreach loop.
var oldData = new List<myObject>();
foreach(var data in myObjectList){
oldData.Add((myObject)data.Clone();
}
This is going “fast” with a small list of objects, but once my list had around 1000 items, it didn’t go fast enough. So after googling the web I found a better solutions. Why not cloning the whole list at once.
To do this I need to let my class inherit from ICloneable interface. Once this is done, you can do the following instead of using the foreach.
var oldData = new List<myObject>();
oldData = (List<myObject>) myObjectList.Clone();
This line of code had a elapsed time around 12seconds instead of 5-6minutes with the foreach loop. Which is away better performance.
Now my program has a smoother way of working. Hope that y’all can also benefit from this.
Greetzz and until next post …