Monday, October 3, 2016

Shallow copy and Deep copy in C#

Shallow copy and Deep copy:

Shallow Copy :Shallow copy copies the reference of that class or object and its don't create new memory to copy the object.

Example:

public MyClass ShallowCopy()
    {
        return (MyClass)this.MemberwiseClone();
    }
/////////////////////////////////////////////////////////////////////////

 class A
    {
        public int a = 0;
        public void display()
        {
            Console.WriteLine("The value of a is " + a);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A ob1 = new A();
            ob1.a = 10;
            A ob2 = new A();
            ob2 = ob1;
            ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 5.
            ob2.display();
            Console.ReadLine();
        }
    }

Output : The value of a is 5
/////////////////////////////////////////////////////////
Deep Copy: copies not only copies the value type but also provide a new memory object with new refrance for refrance type member in the new copy class.

Example:

 public MyClass DeepCopy()
    {
        MyClass temp = (MyClass)this.MemberwiseClone();
        //Creating a new memory for the object and setting same values from the original
        temp.myjob = new Job { Department = this.myjob.Department, job = this.myjob.job };
        return temp;
    }

 class A
    {
        public int a = 0;
        public void display()
        {
            Console.WriteLine("The value of a is " + a);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            A ob1 = new A();
            ob1.a = 10;
            A ob2 = new A();
            ob2.a = ob1.a;

            ob1.a = 5; // <-- If you see value of ob2.a after this line, it will be 10.
            ob1.display();
            ob2.display();
            Console.ReadLine();
        }
    }

OutPut : The value of a is 5
              The value of a is 10