A static method for performing deep copies.
Even for arrays and classes that are normally passed by reference, this allows them to be copied by value.
// Usage: MyClass dest = Deep.Copy(source);
public static class Deep
{
public static T Copy(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;
}
}