C# string reference type?

前端 未结 10 1117
梦如初夏
梦如初夏 2020-11-22 10:10

I know that \"string\" in C# is a reference type. This is on MSDN. However, this code doesn\'t work as it should then:

class Test
{
    public static void          


        
10条回答
  •  盖世英雄少女心
    2020-11-22 10:32

    For curious minds and to complete the conversation: Yes, String is a reference type:

    unsafe
    {
         string a = "Test";
         string b = a;
         fixed (char* p = a)
         {
              p[0] = 'B';
         }
         Console.WriteLine(a); // output: "Best"
         Console.WriteLine(b); // output: "Best"
    }
    

    But note that this change only works in an unsafe block! because Strings are immutable (From MSDN):

    The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

    string b = "h";  
    b += "ello";  
    

    And keep in mind that:

    Although the string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

提交回复
热议问题