Cloning an object in .NET

 
 
  • Gérald Barré

Sometimes you need to clone an object. This can be tedious depending on how many properties the object has. With 10-15 properties it is still manageable, but beyond that the code becomes lengthy and you risk forgetting a property. Here is a generic solution using serialization.

C#
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;
        }
    }
}

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?