C # Shallow copy and deep copy difference

Source: Internet
Author: User
Tags shallow copy

Maybe someone would explain the difference between a shallow copy and a deep copy in C #:

A shallow copy is a copy of an address to a reference type and a direct copy of a value type.

It cannot be said that it is completely wrong, but at least not rigorous enough. For example, what does the string type say?

In fact, we can find the answer through practice.

First, define the following types:

int, string, enum, struct, class, int[], string[]

The code is as follows:

Enumeration
public enum MyEnum
{_1 = 1, _2 = 2}
Structural body
public struct MYSTRUCT
{
public int _int;
Public mystruct (int i)
{_int = i;}
}
Class
Class MyClass
{
public string _string;
Public MyClass (String s)
{_string = s;}
}
ICloneable: Creates a new object as a copy of the current instance.
Class Democlass:icloneable
{
public int _int = 1;
public string _string = "1";
Public MyEnum _enum = myenum._1;
Public MyStruct _struct = new MyStruct (1);
Public MyClass _class = new MyClass ("1");
Array
Public int[] Arrint = new int[] {1};
Public string[] arrstring = new string[] {"1"};
Returns a new object for this instance copy
public Object Clone ()
{
MemberwiseClone: Returns a shallow copy of the current object (which is the base method of the object)
return this. MemberwiseClone ();
}
}

Attention:

ICloneable interface : Supports cloning, which creates a new instance of the class with the same value as an existing instance.

MemberwiseClone method : Creates a shallow copy of the current System.Object.

Next, build instance a , and create an instance Bfor instance a cloning.
Then, change the value of instance B and observe that the value of instance a will not be changed.

The code is as follows:

Class shallow copy and deep copy
{
static void Main (string[] args)
{
DemoClass A = new DemoClass ();
Create a copy of instance a--new object instance B
DemoClass B = (DemoClass) a.clone ();
B._int = 2;
Console.WriteLine ("Int \t\t a:{0} b:{1}", A._int, B._int);
b._string = "2";
Console.WriteLine ("String \ t a:{0} b:{1}", a._string, b._string);
B._enum = myenum._2;
Console.WriteLine ("Enum \t\t a:{0} b:{1}", (int) a._enum, (int) b._enum);
B._struct._int = 2;
Console.WriteLine ("struct \ t a:{0} b:{1}",
A._struct._int, B._struct._int);
b._class._string = "2";
Console.WriteLine ("Class \t\t a:{0} b:{1}",
A._class._string, b._class._string);
B.arrint[0] = 2;
Console.WriteLine ("Intarray \ t a:{0} b:{1}",
A.arrint[0], b.arrint[0]);
B.arrstring[0] = "2";
Console.WriteLine ("Stringarray \ t a:{0} b:{1}",
A.arrstring[0], b.arrstring[0]);
Console.readkey ();
}
}

The results are as follows:

From the final output, we learned that:

Copy an address for the internal class object and array. [Change B, A has also been changed]

For other built-in Int/string/enum/struct/object types, copy a copy of the value.

One netizen said:String type is a reference type, but in many cases. Net handles string as a value type, and I think string should also be handled by value type.

This means that he is not familiar with the string type.

To be sure: string must be a reference type. Then why is it a deep copy?

If you look at the string type of source code, you know:

Represents an empty string. This field is read-only.
public static readonly string Empty;

The answer is that the string is readonly, and when you change the data value of string type, the memory address is reassigned.

here is a reference to a Netizen's code: vseen[Aloner] the Personal burrow see:

public class Student
{
The "field" here, in fact, should be a property.
public string Name;
public int age;
Custom Class Classroom
Public classroom Class;
}
Shallow copy: Student a shallow copy out Student B,name and age have a new memory address, but reference the same classroom.
Deep copy: Student a shallow copy out Student B,name and age have a new memory address, and a.classroom memory address is not equal to b.classroom.
In fact, the vulgar point, a bit like:
public Object Clone ()
{
Student B = new Student ();
B.name = this. Name;
B.age = this. Age;
Shallow copy
B.class = this. Class;
Deep copy
B.class = new Classromm ();
B.class.name = this. Class.name;
B.class.teacher = this. Class.teacher;
Depending on the situation, the teacher is judged by a deep copy or a shallow copy.
}

Shallow copy: Copies a new object to the object.

Shallow copy definition-assigns a new memory address only to a value type (or string) type.


Deep copy: Copies a whole new object to the object.

Deep copy definition--assigns a new memory address to a value type, a reference type, and a new address assigned by the internal field of the reference type.

I am so defined: shallow copy, in the same way.

Attention:

1. In. NET programs, you should avoid using the ICloneable interface.

Because it is not possible to determine whether a shallow copy or a deep copy through the interface, this can cause misunderstanding or misuse.

2, deep copy should copy the object itself and through the object can be reached by the complete object graph, shallow copy only the object itself (that is, the object represented in the heap in a contiguous address of the content).

Personal humble Opinion:

Clone: deep Copy, copied to the value of the memory block pointed to by the pointer.

Shallow copy: copies only the contents of the pointer. (Just give a name to an object, so when you change a property of a copy, the corresponding property of the original object will also change).

C # Shallow copy and deep copy difference

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.