C# string reference type?

前端 未结 10 1204
梦如初夏
梦如初夏 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:16

    "A picture is worth a thousand words".

    I have a simple example here, it's similar to your case.

    string s1 = "abc";
    string s2 = s1;
    s1 = "def";
    Console.WriteLine(s2);
    // Output: abc
    

    This is what happened:

    • Line 1 and 2: s1 and s2 variables reference to the same "abc" string object.
    • Line 3: Because strings are immutable, so the "abc" string object do not modify itself (to "def"), but a new "def" string object is created instead, and then s1 references to it.
    • Line 4: s2 still references to "abc" string object, so that's the output.

提交回复
热议问题