Home >Backend Development >C++ >Why Can't C# Class Fields Be Assigned by Reference, and How Can This Be Worked Around?
Keeping Hold of References When Assigning to a Field
In C#, assigning by "reference" to a class field is not possible. This is because fields cannot be of reference type. There are three main reasons for this:
Reasons for Restriction:
Workaround:
Despite the restriction, there is a workaround to simulate reference-like behavior:
Using a Delegate and Action:
Create a delegate with a getter and setter for the desired value. Store this delegate in a field instead of a ref. For example:
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 }
In this case, x stores a delegate that can get and set the value of y. When you set x.Value, it modifies y.
The above is the detailed content of Why Can't C# Class Fields Be Assigned by Reference, and How Can This Be Worked Around?. For more information, please follow other related articles on the PHP Chinese website!