Can a String object behave like other reference objects such as in the case below?

class MyClass
{
    public String Text = "";
}

MyClass a = new MyClass();
a.Text = "Text in a.Text";
MyClass b = a;
b.Text = "Text in b.Text";
Debug.WriteLine(a.Text); // Prints 'Text in b.Text"
String a = "Text in a";
String b = a;
b = "Text in b";
Debug.WriteLine(a); // Prints 'Text in a"

Is there a way to make the second example so that the end result is 'Text in b'? I thought 'String' was a reference class, then shouldn't the statement 'String b = a' create b as a reference to 'a'?

I'm misunderstanding something fundamental here, any tips appreciated.

- Pops

The statement String b = a copies the reference to b, it doesn't make b reference a. The next line you are setting b to reference a different object (the string "Text in b"), this has no affect on a (and you'll find that all object behave this way, not just string)

The reason this works in the first case is that you aren't changing what b is referencing, you are changing something internal to the object. Since a and b are still referencing the same object, it has that behavior.

please use method and override those methods.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.