Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

Question about c# and string outside the class or function vs string inside a class or function

I know that string is a reference type, but I'm having problem understanding why string outside the "refTest" class or function won't behave like the one inside the class "refTest". I mean if I have 2 string named "name" and "name2", and both have the same value since name2 has a copy of name, it will output the same value "A", but then I change the second string value to "B" and this time name and name2 have different value "A" and "B", and then when I do the same thing with a string that is from a class "refTest" it will output name1 and name2 the same value. Aren't both string reference type? Which means they have a pointer on a heap. Right? I'm getting confused on why string outside the class "refTest" will output a different outcome compared to the one inside the "refTest" class.

Or it is that everytime I declare a string outside the "refTest" class, it will be stored on a different address (heap address)?

class Program
{
    static void Main(string[] args)
    {
        
        string name = "A";
        string name2 = name;
        Console.WriteLine(name2 + " " + name);
        // >> A A
        name2 = "B";
        Console.WriteLine(name2 + " " + name);
        // >> A B


        refTest test = new refTest();
        test.rTName = "A";
        Console.WriteLine(test.rName);
        // >> A
        refTest test2 = test;
        test2.rName = "B";
        Console.WriteLine($"test.rName = {test.rName}, test2.rName = {test2.rName}");
        // >> test.rName = B, test2.rName = B
        Console.ReadLine();
    }

}


class refTest
{
    public string rName;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

string, although is a reference type, it is an immutable one. That means that when you do name2 = "B" you're creating a new instance and making name2 point to the new instance, while name still points to the old one.

Now for your custom class, when you do refTest test2 = test; you're making test2 points to the same object as test, and when you modify a property or field in one of them, as they both points to the same object, both test and test2 will display the new value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...