Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 934
Rohit Raghuvansi Avatar asked Jul 16 '09 10:07

Rohit Raghuvansi


People also ask

Can the value of a variable change during program execution?

A constant is a data item whose value cannot change during the program's execution. Thus, as its name implies – the value is constant. A variable is a data item whose value can change during the program's execution. Thus, as its name implies – the value can vary.

Can data stored by a variable in a computer program be changed during the runtime of the program?

While a variable's name, type, and location often remain fixed, the data stored in the location may be changed during program execution.


2 Answers

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.

like image 159
mmx Avatar answered Sep 19 '22 12:09

mmx


Use Observer pattern. Here's another reference.

like image 45
this. __curious_geek Avatar answered Sep 17 '22 12:09

this. __curious_geek