Whether string in. NET is a reference type or a value type and a C # deep copy shallow copy

Source: Internet
Author: User

Http://www.cnblogs.com/yank/archive/2011/10/24/2204145.html

Http://www.cnblogs.com/zwq194/archive/2012/08/06/2625403.html

The discussion of whether string is a value type or a reference type has not subsided, and has recently been studying performance issues, once again making this issue clear again today. Hope to bring you a little help. Please indicate if there are any errors.

Consider the following example:

            //value type            intA =1; intb =A; A=2; Console.WriteLine ("A is {0},b is {1}", A, b); //string            stringSTR1 ="AB"; stringSTR2 =str1; STR1="ABC"; Console.WriteLine ("str1 is {0},str2 is {1}", str1, str2);    Console.read (); 

According to the above example: what do you think the output should be?

Output Result:

            // results:             // A is 2,b is 1             // str1 is abc,str2 is AB

STR2 is still AB, and does not change with str1.

If the string is a reference type, both the STR1 and STR pointers point to the same memory address, and if the contents of STR change, the STR1 should also change accordingly.

For this example, look at the string more like a value type.

But MSDN says that string is a reference type,

reference types include: String

All arrays, even if their elements are value types

class type, such as Form

Commissioned

Refer to: Http://msdn.microsoft.com/zh-cn/library/t63sy5hs (vs.80). aspx

See if specific references are the same

If NET can see the memory address is easy, but not allowed, can only be implemented by indirect method, see below:

        Static voidtestrefaddress () {String str1="ABC"; String str2="ABC"; intA =1; intb =1; StringBuilder STRB1=NewStringBuilder ("ABC"); StringBuilder STRB2=NewStringBuilder ("ABC"); Console.WriteLine ("Reference Equal for string:"+ object.referenceequals (str1, str2));//result TrueConsole.WriteLine ("Reference equal for int:"+ Object.referenceequals (A, b));//false ResultConsole.WriteLine ("Reference equal for StringBuilder:"+ object.referenceequals (STRB1, STRB2));//false ResultConsole.WriteLine ("Value Equal for string:"+ str1. Equals (STR2));//result true, similar to value typeConsole.read (); }

As a result, the analysis of the situation is as follows:

Console.WriteLine ("Reference Equal for string:"+ object.referenceequals (str1, str2));//result true, different objects, but same reference addressConsole.WriteLine ("Reference equal for int:"+ Object.referenceequals (A, b));//result false, value type boxing operation causesConsole.WriteLine ("Reference equal for StringBuilder:"+ object.referenceequals (STRB1, STRB2));//result false, different object, reference address differentConsole.WriteLine ("Value Equal for string:"+ str1. Equals (STR2));//result true, similar to value type

By the first result, you can determine the different string, the same value, its reference address is the same, and then by the fourth result, str1. Equals (STR2), the combination of the two, can be concluded that two string, if the assignment is the same value, only one string exists in memory, and two references are the same address. This leads to the invariance of the string.

The invariance of a string

One of the most notable features of string is its constant invariance: once we have created a string and allocated a contiguous memory space on the managed heap, we will not be able to modify the string in any way to make it longer, shorter, or more formatted. Any string that is returned by all operations on the string, such as a string that calls ToUpper for uppercase, is actually another string that is recreated and does not itself produce any changes. A string object is called immutable (read-only), because once the object is created, the value of the object cannot be modified. Sometimes it seems to change, actually is a string after a special processing, each time the value is changed to create a new string object, the variable will point to the new object, and the original is still pointing to the original object, so it will not change. This is also the reason why string is inefficient.

The constant string does not mean that the string cannot be changed, but that its value cannot be changed.

In the example str1= "AB", this time in memory, "AB" is saved, if you create a string object, its value is also equal to "AB", str2= "AB", then not re-allocate memory space, but the previous saved "AB" address to str2 reference, This will confirm the results in Example 2. When the value of str1= "ABC" Changes, the memory is checked, the string is not present, the memory space is redistributed, the "ABC" is stored, and the address is assigned to STR1, and str2 still points to the address of "AB". The results in Example 1 can be verified.

Conclusion:

String is a reference type, except that the compiler has handled it specially.

About the discussion: http://social.msdn.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/ce580186-86d9-45f7-b5ff-20302caf1324

About C # deep copy Shallow copy:

There are two types of variables in C #, one is a value type variable and one is a reference type variable. "A shallow copy is a copy of an address on the surface, a deep copy is a copy of the content" for a value type variable, copy is a full copy, whereas for a reference type variable, the general copy is just a shallow copy, which is equivalent to passing only one reference pointer. Therefore, it is also the most troublesome to make a real copy of a reference type variable.

A shallow copy   is just a copy of itself, and it contains objects that simply copy references, and the objects they contain are directly used, and the problem is that if one is modified, the other changes. Yes, but in addition to the string type, the string type, which is originally a reference type, uses a shallow copy when copying, but automatically generates a deep copy when a change occurs. If the field of the object is a value type, both the shallow copy and the deep copy are copied as is.

A deep copy   Not only copies itself, but also copies the objects he contains. If the field of the object is a reference type, then the shallow copy is the copy reference, and the deep copy is the object to copy the reference to.

Whether string in. NET is a reference type or a value type and a C # deep copy shallow copy

Related Article

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.