Why don't we use new operator while initializing a string?

前端 未结 7 919
太阳男子
太阳男子 2020-12-13 06:05

I was asked this question in an interview: Is string a reference type or a value type.

I said its a reference type. Then he asked me why don\'t we use new operator

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 07:09

    Not exactly the right answer. Strings are "special" reference types. They are immutable. You are right that compiler does something internally, but it is not the constructor call. It calls ldstr which pushes a new object reference to a string literal stored in the metadata.

    Sample C# code :

    class Program
    {
        static void Main()
        {
            string str;
            string initStr = "test";
        }
    }
    

    and here is the IL code

    .method private hidebysig static void  Main() cil managed
    {
      .entrypoint
      // Code size       8 (0x8)
      .maxstack  1
      .locals init ([0] string str,
               [1] string initStr)
      IL_0000:  nop
      IL_0001:  ldstr      "test"
      IL_0006:  stloc.1
      IL_0007:  ret
    } // end of method Program::Main
    

    You can see ldstr call above.

    Even more due to immutability of the Strings it becomes possible to keep only distinct/unique strings. All strings are kept in the hash table where the key is the string value and the value is the reference to that string. Each time when we have a new string CLR checks is there already such a string in the hash table. If there is then no new memory is allocated and the reference is set to this existing string.

    You can run this code to check :

    class Program
    {
        static void Main()
        {
            string someString = "abc";
            string otherString = "efg";
    
            // will retun false
            Console.WriteLine(Object.ReferenceEquals(someString, otherString));
    
            someString = "efg";
    
            // will return true
            Console.WriteLine(Object.ReferenceEquals(someString, otherString));
        }
    }    
    

提交回复
热议问题