Home >Backend Development >C++ >Why Doesn't Assigning a Reference Parameter to a Class Field Maintain the Reference in C#?
Referencing Class Fields in C#
In C#, passing a parameter by reference allows for direct modification of the original variable. However, when assigning a reference parameter to a class field, the expected behavior may not occur.
Consider the following code:
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();
Upon execution, the output is "X (Updated By Y)", not "X (Updated By Y) (Updated By Z)" as anticipated.
This is because assigning a reference parameter to a class field breaks the reference. To maintain the reference, a solution is to use a getter and setter:
sealed class Ref<T> { private readonly Func<T> getter; private readonly Action<T> setter; public Ref(Func<T> getter, Action<T> setter) { this.getter = getter; this.setter = setter; } public T Value { get { return getter(); } set { setter(value); } } } Ref<int> x; void M() { int y = 123; x = new Ref<int>(() => y, z => { y = z; }); x.Value = 456; Console.WriteLine(y); // 456 -- setting x.Value changes y. }
In this example, 'x' is an object that can get and set the value of 'y', maintaining the reference between them. Note that while ref locals and ref-returning methods are supported in the CLR, they are not yet available in C#.
The above is the detailed content of Why Doesn't Assigning a Reference Parameter to a Class Field Maintain the Reference in C#?. For more information, please follow other related articles on the PHP Chinese website!