Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Shallow Copy
2.1.
Example
3.
Deep Copy
3.1.
Example
4.
Comparison
5.
Frequently Asked Questions
5.1.
What is the main difference between shadow copy and deep copy?
5.2.
What is Prototype Design Pattern?
5.3.
What is the use of the MemberwiseClone() method?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Shadow Copy and Deep Copy in C#

Author Nagendra
2 upvotes
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

C# is pronounced C sharp. It is a very famous programming language built by Microsoft and operates on the .Net framework. It is closely related to the C programming language, as well as other programming languages such as C++ and Java. Its most impressive feature is its reusability. The language is easy to learn and understand. In the Prototype Design Pattern, the objects are copied using both shallow and deep copies. So, in this blog, we'll look at what Shadow Copy and Deep Copy are, as well as the differences between them.

Recommended Topic, Palindrome in C#, singleton design pattern in c# and  Ienumerable vs Iqueryable

Shallow Copy

Shallow copying entails creating a new object and then copying the non-static fields of the existing object to the new one. If the field is of type value, a bit-by-bit duplication is performed. The original object and its clone refer to the same object since the reference is copied, but the referred object is not. The shallow copy of an object is a new object that shares the original's instance variables. Shallow copying is performed by the .Net object method MemberwiseClone().
The shallow copy can be used if you have an object with values and wish to duplicate it in another variable of the same type. All property values of value kinds will be replicated, but you will only have a reference to that instance if you have a property of reference type.

Example

The shallow copy creates a new object from an existing one and then replicates the old object's value type fields to the new one. In contrast, the reference type will only copy the reference, not the referred object. The original and clone relate to the same item in the case of reference type. Consider the following code snippet.

Code:

using System;
namespace PrototypeDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student();
            s1.Name = "John"; //assigning value
            s1.Department = "CSE"; //assigning value
            s1.StudAddress = new Address() { address = "Delhi"};

            Student s2 = s1.GetClone();
            s2.Name = "Jenny"; //assigning value
            s2.StudAddress.address = "Mumbai"; //assigning value

            Console.WriteLine("Student 1: ");
            Console.WriteLine("Name: " + s1.Name + ", Address: " + s1.StudAddress.address + ", Dept: " + s1.Department);
            Console.WriteLine("Student 2: ");
            Console.WriteLine("Name: " + s2.Name + ", Address: " + s2.StudAddress.address + ", Dept: " + s2.Department);

            Console.Read();
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Department { get; set; }
        public Address StudAddress { get; set; }

        public Student GetClone()
        {
            return (Student)this.MemberwiseClone();
        }
    }

    public class Address
    {
        public string address { get; set; }
    }
}

Output:

Student 1:
Name: John, Address: Mumbai, Dept: CSE
Student 2:
Name: Jenny, Address: Mumbai, Dept: CSE

Explanation:

We update the address and name of the second student, s2, in the above code after establishing the second Student object. It is observed that the address for the s1 has also been modified.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Deep Copy

Deep copy is the process of creating a new object and then copying the non-static fields from the old object to the new object. If the field is of type value, a bit-by-bit duplication is performed. If a field is of the reference type, a new copy of the referred object is produced. The deep duplicate of an object is a brand-new object with brand-new instance variables that share no objects with the original. During Deep Copy, the classes to be cloned must be tagged as [Serializable]. Deep copy replicates every element of an object, including directly referenced value type elements and indirectly referred reference type elements that store a reference to a memory location containing data.

Example

The Deep copy will generate a new object from an existing object and then copy the fields from the old object to the newly produced object. If the field is of the value type, a bit-by-bit copy of the field will be made. A new copy of the referred object is created if the field is of the reference type. Consider the following code snippet:

Code:

using System;
namespace PrototypeDesignPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student();
            s1.Name = "John"; //assigning value
            s1.Department = "CSE"; //assigning value
            s1.StudAddress = new Address() { address = "Delhi"};
            Student s2 = s1.GetClone();
            s2.Name = "Jenny"; //assigning value
            s2.StudAddress.address = "Mumbai"; //assigning value
            Console.WriteLine("Student 1: ");
            Console.WriteLine("Name: " + s1.Name + ", Address: " + s1.StudAddress.address + ", Dept: " + s1.Department);
            Console.WriteLine("Student 2: ");
            Console.WriteLine("Name: " + s2.Name + ", Address: " + s2.StudAddress.address + ", Dept: " + s2.Department);
            Console.Read();
        }
    }
    public class Student
    {
        public string Name { get; set; }
        public string Department { get; set; }
        public Address StudAddress { get; set; }
        public Student GetClone()
        {
            Student s = (Student)this.MemberwiseClone();
            s.StudAddress = StudAddress.GetClone();
            return s;
        }
    }
    public class Address
    {
        public string address { get; set; }
        public Address GetClone()
        {
            return (Address)this.MemberwiseClone();
        }
    }
}

Output:

Student 1:
Name: John, Address: Delhi, Dept: CSE
Student 2:
Name: Jenny, Address: Mumbai, Dept: CSE

Explanation:

Here, when a new object is created, new memory space is allocated irrespective of the values assigned to it. Hence we have different values for both s1 and s2.

Let's compare shallow and deep copy to get a better understanding of the topic.

Comparison

Frequently Asked Questions

What is the main difference between shadow copy and deep copy?

The shallow copy entails creating a new collection object and then populating it with references whereas in deep copy a new object is created and then recursively populate it with the copies of original’s chile object.

What is Prototype Design Pattern?

The Prototype design pattern outlines the kind of things that should be created using a prototypical instance and how additional objects should be created by duplicating this prototype.

What is the use of the MemberwiseClone() method?

The MemberwiseClone() method generates a shallow copy by establishing a new object and then copying the non-static fields of the current object to the new object.

Conclusion

In this article, we have extensively discussed the shadow copy and deep copy in C#. The article explains the detailed explanation and comparison of shadow copy and deep copy in C# with examples.
We hope that this blog has helped you enhance your knowledge regarding the shadow copy and deep copy in C# and if you would like to learn more, check out our articles on C#. You can refer to our guided paths on the Coding Ninjas Studio platform to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. To practice and improve yourself in the interview, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews.

Recommended Readings:

C# interview questions for 5 years Experience

Do upvote our blog to help other ninjas grow. 

Happy Coding!!

Previous article
Partial Classes in C#
Next article
Object and Collection Initializer in C#
Live masterclass