0

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

3
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by ashishkumar008
1

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.