Click here to Skip to main content
15,885,985 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.3K   1.1K   53  
Shallow and deep copy are used for copying data between objects.
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class clsShallow
{
    public static string CompanyName = "My Company";
    public int Age;
    public string EmployeeName;
    public clsRefSalary EmpSalary;

    public clsShallow CreateShallowCopy(clsShallow inputcls)
    {
        return (clsShallow)inputcls.MemberwiseClone();
    }
}
[Serializable]
// serialize the classes in case of deep copy
public class clsDeep
{
    public static string CompanyName = "My Company";
    public int Age;
    public string EmployeeName;
    public clsRefSalary EmpSalary;
    public clsDeep CreateDeepCopy(clsDeep inputcls)
    {
        MemoryStream m = new MemoryStream();
        BinaryFormatter b = new BinaryFormatter();
        b.Serialize(m, inputcls);
        m.Position = 0;
        return (clsDeep)b.Deserialize(m);
    }
}

[Serializable]
public class clsRefSalary
{
    public clsRefSalary(int _salary)
    {
        Salary = _salary;
    }
    public int Salary;

    /// <summary>
    /// Using generics will solve some performance issues
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="item"></param>
    /// <returns></returns>
    public static T DeepCopy<T>(T item)
    {
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream stream = new MemoryStream();
        formatter.Serialize(stream, item);
        stream.Seek(0, SeekOrigin.Begin);
        T result = (T)formatter.Deserialize(stream);
        stream.Close();
        return result;
    }

}


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