How can I execute code when value of a variable changes in C#?
c#, delegates, variables
Solution
No, you can't do things like overloading assignment operator in C#. The best you could do is to change the variable to a property and call a method or delegate or raise an event in its setter.
private string field;
public string Field {
get { return field; }
set {
if (field != value) {
field = value;
Notify();
}
}
}
This is done by many frameworks (like WPF `DependencyProperty` system) to track property changes.
Problem
I want to toggle a button's visibility in when value of a particular variable changes. Is there a way to attach some kind of delegate to a variable which executes automatically when value changes?