ref as class members?

  • Thread starter Thread starter Christer Eckard
  • Start date Start date
C

Christer Eckard

Hi,

I am quite new to C# (but not to C++).
Could anyone tell me if it is possible to store a ref to a string in a
class in C#? If not possible please tell me, if possible, please
explain how..

Something like this:

string test = "not modified";
MyStringModifier msm = new MyStringModifier(ref test);
msm.modify();
MessageBox.Show(test); // I want this to show "changed!" Is it
possible?


public class MyStringModifier
{
string thestring; // I want this to be a ref to the string...

public MyStringModifier(ref string somestring)
{
thestring = somestring; // i know, this makes I copy, what I want is
// for the 'thestring' to exactly the same this as somestring..
// a ref to the outside string
}
public void modify()
{
thestring = "changed!";
}
}

I know I could use the function to return a new string or something..
But I would be nice to know if this is possible. I also know that
strings
are inmutable in C#, I want the actual pointer to be changed just is
if I
directly changed the ref variable.

/chris
 
Christer Eckard said:
I am quite new to C# (but not to C++).
Could anyone tell me if it is possible to store a ref to a string in a
class in C#?

Yes, but that's not what it looks like you actually want. It sounds
like what you want is actually a reference to a *variable* - and no,
you can't do this (in that kind of way, anyway - you could use
reflection in some cases, but it would be messy).

I know I could use the function to return a new string or something..
But I would be nice to know if this is possible. I also know that
strings are inmutable in C#, I want the actual pointer to be changed just is
if I directly changed the ref variable.

Apart from anything else, I'd view this as a really bad idea in terms
of creating unreadable code. Variables changing their values
unexpectedly is a nasty situation to have to debug, IMO.

You could, however, make a mutable string wrapper - i.e. an object
which contains a string reference, and that string reference can be
changed and retrieved.
 
Back
Top