Mutability of string when string doesn't change in C#

和自甴很熟 提交于 2019-11-29 12:56:38
Shamseer K

No, a new instance will be created only when the string operation changes the value in the string variable.

It can be proved using the ObjectIDGenerator class. It's worth reading this complete article for proof.

using System;
using System.Text;
using System.Runtime.Serialization;

namespace StringVsStringBuilder
{
    class Program
    {
        static void Main(string[] args)
        {
            ObjectIDGenerator idGenerator = new ObjectIDGenerator();
            bool blStatus = new bool();
            // blStatus indicates whether the instance is new or not
            string str = "Fashion Fades,Style Remains Same";
            Console.WriteLine("Initial state");
            Console.WriteLine("str = {0}", str);
            Console.WriteLine("Instance id: {0}", idGenerator.GetId(str, out blStatus));
            Console.WriteLine("This is new instance: {0}", blStatus);
            // A series of operations that won't change value of str
            str += "";

            // Try to replace character 'x' which is not present in str so no change
            str = str.Replace('x', 'Q');

            // Trim removes whitespaces from both ends so no change
            str = str.Trim();
            str = str.Trim();
            Console.WriteLine("\nFinal state");
            Console.WriteLine("str = {0}", str);
            Console.WriteLine("Instance id: {0}", idGenerator.GetId(str, out blStatus));
            Console.WriteLine("This is new instance: {0}", blStatus);
            Console.ReadKey();
        }
    }
}

No it doesn't. You can simply test it using object.ReferenceEquals() as follows:

        string s = "test";
        string q = s;
        s += "";
        bool eq1 = object.ReferenceEquals(s, q); //--> References are equal
        s += "1";
        bool eq2 = object.ReferenceEquals(s, q); //--> References are not equal any more 

String.Concat(string,string), which is normally what the compiler turns string 'addition' into, checks if one of the arguments is null or empty, and returns the non-NullOrEmpty argument. So in your example, it will simply return str, and no object is created.

In reality though, the compiler may optimize away your entire operation, noticing that you're just concatenating an empty string. A better test would be where both values are variables, and one happens to contain an empty string.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!