Home  >  Article  >  Backend Development  >  What is shallow copy and how is it different from deep copy in C#?

What is shallow copy and how is it different from deep copy in C#?

王林
王林forward
2023-09-06 19:41:09542browse

什么是浅复制以及它与 C# 中的深复制有何不同?

Shallow copy

Shallow copy refers to copying the "main" part of an object, but not copying the internal parts objects.

The "inner objects" are shared between the original object and its copy.

The problem with the shallow copy is that the two objects are not independent. If you Modify one object and the changes will be reflected in the other object.

Deep copy

Deep copy is a completely independent copy of the object. If we copy our object, would copy the entire object structure.

If you modify the one object, the change will not be reflected in the other object.

Example

class Program{
   static void Main(string[] args){
      //Shallow Copy
      ShallowCopy obj = new ShallowCopy();
      obj.a = 10;
      ShallowCopy obj1 = new ShallowCopy();
      obj1 = obj;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); // 10,10
      obj1.a = 5;
      Console.WriteLine("{0} {1}", obj1.a, obj.a); //5,5
      //Deep Copy
      DeepCopy d = new DeepCopy();
      d.a = 10;
      DeepCopy d1 = new DeepCopy();
      d1.a = d.a;
      Console.WriteLine("{0} {1}", d1.a, d.a); // 10,10
      d1.a = 5;
      Console.WriteLine("{0} {1}", d1.a, d.a); //5,10
      Console.ReadLine();
   }
}
class ShallowCopy{
   public int a = 10;
}
class DeepCopy{
   public int a = 10;
}

Output

10 10
5 5
10 10
5 10

The above is the detailed content of What is shallow copy and how is it different from deep copy in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete