How can I execute the code when the value of a variable changes to C #?

I want to switch the button visibility when changing the value of a specific variable. Is there a way to bind some delegate to a variable that automatically executes when the value changes?

+7
variables c # delegates
source share
5 answers

No, you cannot do things like overloading an assignment operator in C #. The best you can do is change the variable to a property and call the method or delegate or raise the event in your setter.

private string field; public string Field { get { return field; } set { if (field != value) { field = value; Notify(); } } } 

This is done by many frameworks (for example, the WPF DependencyProperty system) to track property changes.

+18
source share
+3
source share

You can also use data binding: in WPF , in Windows Forms . This allows you to change the state of the graphical interface depending on the properties of objects and vice versa.

+2
source share

There is no way to do this. Variables are simply places in memory that your application writes.

Use the property instead:

 string myVariable; public string MyVariable { get { return myVariable; } set { myVariable = value; MyVariableHasBeenChanged(); } } private void MyVariableHasBeenChanged() { } 
+1
source share

You have a link to the graphical interface in your model (where there is a variable) and directly make changes to the graphical interface in the setter method, or you make your GUI monitor your model through an observer and have observed fire events of the model to observers in the setters. The former will lead to the spaghetti code in the end, as you add more direct links between the model and the view, and therefore should only be used for internal tools and simple programs.

0
source share

All Articles