ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DeepClone

It returns deep copy of the object.

Source

public static T DeepClone<T>(this T input) where T : ISerializable
{
   using (var stream = new MemoryStream())
   {
      var formatter = new BinaryFormatter();
      formatter.Serialize(stream, input);
      stream.Position = 0;
      return (T)formatter.Deserialize(stream);
   }
}

Example

var stringbuilder = new StringBuilder("TestData");
var copy = stringbuilder.DeepClone();
Assert.IsFalse(Equals(stringbuilder,copy));

Author: Omkar Panhalkar

Submitted on: 7 mei 2012

Language: C#

Type: System.Type

Views: 13332