Click here to Skip to main content
Click here to Skip to main content
Articles » Languages » C# » Memory Management » Downloads
 
Add your own
alternative version

Shallow Copy vs. Deep Copy in .NET

, 10 Oct 2008
Shallow and deep copy are used for copying data between objects.
ShallowVsDeep.zip
ShallowVsDeep
bin
Debug
ShallowVsDeep.exe
obj
Debug
TempPE
Properties
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)

About the Author

Ahmad Eid Salim
Software Developer (Senior)
Egypt Egypt
No Biography provided

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 11 Oct 2008
Article Copyright 2008 by Ahmad Eid Salim
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid