I have a generic list of objects in C#, and wish to clone the list. The items within the list are cloneable, but there doesn\'t seem to be an option to do list.Clone()
My friend Gregor Martinovic and I came up with this easy solution using a JavaScript Serializer. There is no need to flag classes as Serializable and in our tests using the Newtonsoft JsonSerializer even faster than using BinaryFormatter. With extension methods usable on every object.
Standard .NET JavascriptSerializer option:
public static T DeepCopy(this T value)
{
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(value);
return js.Deserialize(json);
}
Faster option using Newtonsoft JSON:
public static T DeepCopy(this T value)
{
string json = JsonConvert.SerializeObject(value);
return JsonConvert.DeserializeObject(json);
}