Deep copy in C#

Deep Copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must use IClonable Interface.

// Program: Deep Copy
// Purpose: Training period
// By: H.M. Saiful Islam

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

namespace DeepCopy
{
    class Program
    {
        static void Main(string[] args)
        {
            Cloner mySource = new Cloner(5);
            Cloner myTarget = (Cloner)mySource.Clone();
            Console.WriteLine("value: {0}", myTarget.MyContent.Val);
            mySource.MyContent.Val = 10;
            Console.WriteLine("value: {0}", myTarget.MyContent.Val);
            Console.ReadKey();
        }

        public class Content
        {
            public int Val;
        }

        public class Cloner : ICloneable
        {
            public Content MyContent = new Content();

            public Cloner(int newVal)
            {
                MyContent.Val = newVal;
            }

            #region ICloneable Members

            public object Clone()
            {
                Cloner CC = new Cloner(MyContent.Val);
                return CC;
            }

            #endregion
        }

    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s