Cloning an object in .NET

  • .NET

Sometimes you need to clone an object. This can be tedious depending on the number of properties. Up to 10-15 there are not too many problems, but then it gets long and you may forget one property. Here is a generic solution for cloning objects. The principle: use serialization.

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

public Class Test : IClonable
{
    public object Clone()
    {
        using(MemoryStream ms = new MemoryStream())
        {
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(ms, this);
            ms.Position = 0;
            object obj = bf.Deserialize(ms);
            return obj;
        }
    }
}
Follow me:
Enjoy this blog?Buy Me A CoffeeDonate with PayPal

Leave a reply