Monday 9 June 2014

Clone .NET objects

Making clones of objects is quite a regular requirement in .NET projects. Some of the typical scenarios are:

  1. Provide undo functionality in user forms in:
    • Desktop applications e.g. Windows Forms application, WPF application
    • Rich client applications e.g. Silverlight (I know it is most probably not going to have a new version but SL5 will be supported till 2021)
  2. Duplicate a record retrieved from data store

There are a few tried and tested methods which can help in solving this.

Method # 1:
Use Automapper. That is probably the easiest way. e.g. Suppose we have classes like these:

public class FormA
{
        public string FormName { get; set; }

       // public string TestString { get; set; }

        public FormB FormB { get; set; }
}

public class FormB
{
        public string FormName { get; set; }

}

Application code can be like following:

Mapper.CreateMap();
Mapper.CreateMap();
FormA f = new FormA() { FormName = "Test", FormB = new FormB() { FormName = "test2" } };
FormA f1 = new FormA();
Mapper.Map(f, f1);
Console.WriteLine(f1.FormName);
Console.WriteLine(f1 == f);

Console.WriteLine(f1.FormB == f.FormB);

Method# 2:
Use serialization process with any of the preferred formatters (XML, Binary, JSON etc.). Plenty of examples are available on the Internet for this e.g. here. If we use binary formatter, we can preserve value of private members too as binary serialization preserves type fidelity.

Method#3:
Write a generic copy method that Use Reflection to copy values of properties, members etc. It will turn out to be a very involved implementation as it will need to handle null values of members, and type of members (arrays, lists, enums etc.) but it will also provide flexibility to handle any case.

Method#4:
Implement ICloneable to implement the cloning logic.

No comments:

Post a Comment