String as a reference

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
 
J

Jon Skeet [C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top