C# string reference type?

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

    As others have stated, the String type in .NET is immutable and it's reference is passed by value.

    In the original code, as soon as this line executes:

    test = "after passing";
    

    then test is no longer referring to the original object. We've created a new String object and assigned test to reference that object on the managed heap.

    I feel that many people get tripped up here since there's no visible formal constructor to remind them. In this case, it's happening behind the scenes since the String type has language support in how it is constructed.

    Hence, this is why the change to test is not visible outside the scope of the TestI(string) method - we've passed the reference by value and now that value has changed! But if the String reference were passed by reference, then when the reference changed we will see it outside the scope of the TestI(string) method.

    Either the ref or out keyword are needed in this case. I feel the out keyword might be slightly better suited for this particular situation.

    class Program
    {
        static void Main(string[] args)
        {
            string test = "before passing";
            Console.WriteLine(test);
            TestI(out test);
            Console.WriteLine(test);
            Console.ReadLine();
        }
    
        public static void TestI(out string test)
        {
            test = "after passing";
        }
    }
    

提交回复
热议问题