I’d like to assign a reference to a member field. But I obviously do not understand this part of C# very well, because I failed 🙂 So, here’s my code:
public class End {
public string parameter;
public End(ref string parameter) {
this.parameter = parameter;
this.Init();
Console.WriteLine("Inside: {0}", parameter);
}
public void Init() {
this.parameter = "success";
}
}
class MainClass {
public static void Main(string[] args) {
string s = "failed";
End e = new End(ref s);
Console.WriteLine("After: {0}", s);
}
}
Output is:
Inside: failed
After: failed
How do I get “success” on the console?
Thanks in advance,
dijxtra
There are really two issues here.
One, as the other posters have said, you can’t strictly do what you’re looking to do (as you may be able to with C and the like). However – the behavior and intent are still readily workable in C# – you just have to do it the C# way.
The other issue is your unfortunate attempt to try and use strings – which are, as one of the other posters mentioned – immutable – and by definition get copied around.
So, having said that, your code can easily be converted to this, which I think does do what you want: