String as a reference

  • Thread starter Thread starter Nenad Dobrilovic
  • Start date Start date
N

Nenad Dobrilovic

Hi,
I have two references to the same string, like this:

string s1 = "One";
string s2 = s1;

s1 = "Two"; <--- s2 is still referencing to "One"

Now, I want that when I change the value of one variable (s1), the other
one (s2) is changed also. Can string behave like all other reference types?
Can it be done?

Thanx,
Cheya
 
Nenad Dobrilovic said:
I have two references to the same string, like this:

string s1 = "One";
string s2 = s1;

s1 = "Two"; <--- s2 is still referencing to "One"

Now, I want that when I change the value of one variable (s1), the other
one (s2) is changed also.

You can't do that.
Can string behave like all other reference types?

String already *does* behave like all other reference types. Changing
the value of one reference type variable doesn't change the value of
any other reference type variable. Note that there's a big difference
between changing the value of a variable and making a change within the
object that a variable's value refers to.
Can it be done?

Well, you could write a StringHolder class which contained a reference
to a string and allowed it to be changed to a different reference. You
can't do it with plain string though.
 
Back
Top