Click here to Skip to main content
15,896,606 members
Articles / Programming Languages / C#

Shallow Copy vs. Deep Copy in .NET

Rate me:
Please Sign up or sign in to vote.
3.25/5 (50 votes)
10 Oct 2008CPOL3 min read 256.7K   1.1K   53  
Shallow and deep copy are used for copying data between objects.
using System;
using System.Collections.Generic;
using System.Text;

namespace ShallowVsDeep
{
    class Program
    {
        static void Main(string[] args)
        {
            clsRefSalary clsref; int EmpSalary;
            //
            Console.Write("Shallow Copy Tracing:\n---------------------------------\n");
            // Creates an instance of clsShallow and assign values to its fields.
            clsShallow objshallow = new clsShallow();
            objshallow.Age = 25;
            objshallow.EmployeeName = "Ahmed Eid";

            // add the ref value
            clsref = new clsRefSalary(1000);
            objshallow.EmpSalary = clsref;

            // Performs a shallow copy of m1 and assign it to m2.
            clsShallow m2 = objshallow.CreateShallowCopy(objshallow);

            clsShallow m3 = m2;

            // then modify the clsref salary value to be 2000 
            clsref.Salary = 2000;

            // so the m1 object salary value become 2000
            EmpSalary = objshallow.EmpSalary.Salary;

            Console.Write("Name: {0}\nAge: {1}\nSalary: {2}\n\n",objshallow.EmployeeName,objshallow.Age,objshallow.EmpSalary.Salary);

            Console.Write("Deep Copy Tracing:\n---------------------------------\n");
            // Creates an instance of clsDeep and assign values to its fields.
            clsDeep objdeep = new clsDeep();
            objdeep.Age = 25;
            objdeep.EmployeeName = "Ahmed Eid";

            // add the ref value
            clsref = new clsRefSalary(1000);
            objdeep.EmpSalary = clsref;

            // Performs a shallow copy of m1 and assign it to m2.
            clsDeep m4 = objdeep.CreateDeepCopy(objdeep);

            clsDeep m5 = m4;

            // then modify the clsref salary value to be 2000 
            clsref.Salary = 2000;

            // so the m1 object salary value become 2000
            EmpSalary = objdeep.EmpSalary.Salary;

            Console.Write("Name: {0}\nAge: {1}\nSalary: {2}\n\n", objshallow.EmployeeName, objshallow.Age, objshallow.EmpSalary.Salary);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Egypt Egypt
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions