0

If the string operation doesn't change the value of string, will that end up in creation of a new instance?

For example,

string str = "foo";
str += "";

I know the difference between string and StringBuilder in C#.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
samurai
  • 68
  • 7

3 Answers3

3

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 
Arin Ghazarian
  • 4,311
  • 2
  • 16
  • 21
3

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();
        }
    }
}

Enter image description here

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Shamseer K
  • 4,104
  • 1
  • 21
  • 35
2

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.