A day with .Net

My day to day experince in .net

Archive for January, 2013

Deep Cloning in C# by Extension Methods

Posted by vivekcek on January 11, 2013

In this code sample i will show you how to implement deep cloning by Extension methods.

1. Create a console project.

2. Add Serializable class Employee

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeepClone
{
    [Serializable]
    class Employee
    {
        public string Name = string.Empty;
    }
}

3. Now write an Extension method by adding a static class.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace DeepClone
{
    public static class ExtensionMethods
    {
        public static T DeepClone<T>(this T toClone)
        {
            using (var stream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(stream, toClone);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    }
}

4. Now in Program.cs write this code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeepClone
{
    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("//Normal object assigning///");
            Employee emp = new Employee();
            emp.Name = "Vivek";
            Console.WriteLine("Employee Name before shallow copy: " + emp.Name);
            Employee emp1 = emp;
            emp1.Name = "Chanthu";
            Console.WriteLine("Employee Name after shallow copy: " + emp.Name);

            Console.WriteLine("//Deep clone///");

            Employee em = new Employee();
            em.Name = "Vivek";
            Console.WriteLine("Employee Name before shallow copy: " + em.Name);
            Employee em1 = em.DeepClone();
            emp1.Name = "Chanthu";
            Console.WriteLine("Employee Name after shallow copy: " + em.Name);

            Console.Read();

        }
    }
}

Posted in c#.net | Tagged: | Leave a Comment »