A static utility method for performing deep copies. Even arrays and class instances — which are normally passed by reference — can be duplicated by value.
// Usage: MyClass dest = Deep.Copy(source);
public static class Deep
{
public static T Copy<T>(T target)
{
T result;
BinaryFormatter b = new BinaryFormatter();
MemoryStream mem = new MemoryStream();
try
{
b.Serialize(mem, target);
mem.Position = 0;
result = (T)b.Deserialize(mem);
}
finally
{
mem.Close();
}
return result;
}
}