Cloning an object in .NET

 
 
  • Gérald Barré

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.

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?Buy Me A Coffee💖 Sponsor on GitHub