Why strings behave like ValueType

后端 未结 7 2001
感动是毒
感动是毒 2020-12-16 23:44

I was perplexed after executing this piece of code, where strings seems to behave as if they are value types. I am wondering whether the assignment operator is operating on

7条回答
  •  眼角桃花
    2020-12-17 00:02

    The first reason is String is an immutable class.

    An object qualifies as being called immutable if its value cannot be modified once it has been created. For example, methods that appear to modify a String actually return a new String containing the modification. Developers are modifying strings all the time in their code. This may appear to the developer as mutable - but it is not. What actually happens is your string variable/object has been changed to reference a new string value containing the results of your new string value. For this very reason .NET has the System.Text.StringBuilder class. If you find it necessary to modify the actual contents of a string-like object heavily, such as in a for or foreach loop, use the System.Text.StringBuilder class.


    For example:

    string x= 123 ;

    if you do x= x + abc what it does is it assigns new memory location for 123 and abc. Then adds the two strings and places the computed results in new memory location and points x to it.

    if you use System.Text.StringBuilder sb new System.Text.StringBuilder( 123 ); sb.Append( abc ); x sb.ToString();

    stringbuilder is mutable class. It just adds the string to same memory location. This way string manipulation is faster.


    A string is an object of type String whose value is text. Internally, the text is stored as a readonly collection of Char objects, each of which represents one Unicode character encoded in UTF-16.

提交回复
热议问题