It doesn't make sense to set a field as a reference type (private ref bool _val;
) since it is just a class scoped variable. Property setters don't allow you to add the ref
modifier to the automatic value
parameter, so that would not work either. Furthermore, you cannot pass a property as a ref
parameter (i.e. obj1.Method(ref obj2.Value)
will not work).
I think what you are trying to describe is the observer pattern, where observers watch for changes in a subject's state and react. It's similar to an event listener in JavaScript, but instead of watching actions, you are watching state. A simple implementation of this might look like:
public class Subject
{
private readonly Observer[] Observers;
private string _val;
public string Val
{
get => _val;
set
{
// Update every observer's value when this is set.
foreach (Observer o in Observers)
{
o.Val = value;
}
_val = value;
}
}
public Subject(params Observer[] observers)
{
Observers = observers;
}
}
public class Observer
{
public string Val { get; set; }
}
// In execution:
var o1 = new Observer();
var o2 = new Observer();
var subject = new Subject(o1, o2);
subject.Val = "hello there";
Console.WriteLine("o1: " + o1.Val);
Console.WriteLine("o2: " + o2.Val);
Console.WriteLine("subject: " + subject.Val);
// Output:
// o1: hello there
// o2: hello there
// subject: hello there
Note this particular case has some limitations since the relationship only works from Subscriber
to Observer
(i.e., if you change the Observer's Val
directly, it won't be reflected by the other observers and further updates to Subject will overwrite any changes to Observer).