C# string reference type?

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

    If we have to answer the question: String is a reference type and it behaves as a reference. We pass a parameter that holds a reference to, not the actual string. The problem is in the function:

    public static void TestI(string test)
    {
        test = "after passing";
    }

    The parameter test holds a reference to the string but it is a copy. We have two variables pointing to the string. And because any operations with strings actually create a new object, we make our local copy to point to the new string. But the original test variable is not changed.

    The suggested solutions to put ref in the function declaration and in the invocation work because we will not pass the value of the test variable but will pass just a reference to it. Thus any changes inside the function will reflect the original variable.

    I want to repeat at the end: String is a reference type but since its immutable the line test = "after passing"; actually creates a new object and our copy of the variable test is changed to point to the new string.

提交回复
热议问题