Reference Assignments in C# Class Fields
In C#, attempting to assign by "reference" to a class field may result in unexpected behavior. 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();
The expected output is "X (Updated By Y) (Updated By Z)", but instead, only "X (Updated By Y)" is printed. This behavior occurs because assigning a "ref parameter" to a field loses the reference.
Why Can't Fields Hold References?
There are only three possible options when considering fields of "ref type":
Option 1 was chosen to ensure program stability and prevent the creation of time bombs in the code.
How to Achieve Reference-Like Behavior
While you cannot have fields of ref type, there are alternative ways to achieve reference-like behavior:
The above is the detailed content of Why Doesn't C# Allow Fields to Hold References, and What Are the Alternatives?. For more information, please follow other related articles on the PHP Chinese website!