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

王林
Release: 2023-09-06 19:41:09
forward
602 people have browsed it

什么是浅复制以及它与 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;
}
Copy after login

Output

10 10
5 5
10 10
5 10
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template