How do I assign by "reference" to a class field in c#?
Posted
by Jamie
on Stack Overflow
See other posts from Stack Overflow
or by Jamie
Published on 2010-06-05T13:11:56Z
Indexed on
2010/06/05
13:32 UTC
Read the original article
Hit count: 252
I am trying to understand how to assign by "reference" to a class field in c#.
I have the follwing example to consider:
public class X
{
public X()
{
string example = "X";
new Y( ref example );
new Z( ref example );
System.Diagnostics.Debug.WriteLine( example );
}
}
public class Y
{
public Y( ref string example )
{
example += " (Updated By Y)";
}
}
public class Z
{
private string _Example;
public Z( ref string example )
{
this._Example = example;
this._Example += " (Updated By Z)";
}
}
var x = new X();
When running the above code the output is:
X (Updated By Y)
And not:
X (Updated By Y) (Updated By Z)
As I had hoped.
It seems that assigning a "ref parameter" to a field loses the reference.
Is there any way to keep hold of the reference when assigning to a field?
Thanks.
© Stack Overflow or respective owner