C# string reference type?

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 Main()
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(test);
        Console.WriteLine(test);
    }

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

The output should be “before passing” “after passing” since I’m passing the string as a parameter and it being a reference type, the second output statement should recognize that the text changed in the TestI method. However, I get “before passing” “before passing” making it seem that it is passed by value not by ref. I understand that strings are immutable, but I don’t see how that would explain what is going on here. What am I missing? Thanks.

11 Answers
11

Leave a Comment