BeFruit

Tuesday, July 22, 2008

Clone objects in C#

It is simple to clone objects (i.e. make an exact copy of an object) that implement the IClonable interface. It has the Clone() method that you just have to call.

When the method is not available and the class is serializable (has the Serializable attribute), it is possible to use this feature. There are some examples over the Internet, here is a variant I adapted as a templated method:
private static T Clone<T>(T original)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, original);
ms.Flush();
ms.Position = 0;
return (T)bf.Deserialize(ms);
}

You call it this way:
MyClass copy = Clone<MyClass>(original);


But what to do with a non serializable object? The only way is to use reflection. Here is a simplified but working example. One should take care of readable and writable properties.
private static T Clone<T>(T original)
{
T copy = (T)(typeof(T).GetConstructor(System.Type.EmptyTypes).Invoke(null));
foreach (PropertyInfo pi in typeof(T).GetProperties())
{
object originalValue = pi.GetValue(original, null);
pi.SetValue(copy, originalValue, null);
}
return copy;
}

Labels:

0 Comments:

Post a Comment



<$I18N$LinksToThisPost>:

Create a Link

<< Home