Rohit Raghuvansi
Rohit Raghuvansi

Reputation: 2864

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?

Upvotes: 9

Views: 5857

Answers (5)

Alexey Romanov
Alexey Romanov

Reputation: 170919

You can also use Data Binding: in WPF, in Windows Forms. This allows you to change the state of GUI depending on objects' properties and vice versa.

Upvotes: 2

weiqure
weiqure

Reputation: 3235

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

Use a property instead:

string myVariable;
public string MyVariable
{
    get
    {
        return myVariable;
    }
    set
    {
        myVariable = value;
        MyVariableHasBeenChanged();
    }
}

private void MyVariableHasBeenChanged()
{

}

Upvotes: 1

this. __curious_geek
this. __curious_geek

Reputation: 43217

Use Observer pattern. Here's another reference.

Upvotes: 5

JeeBee
JeeBee

Reputation: 17556

You either have a reference to the GUI in your model (where the variable is) and directly perform the GUI change in the setter method, or you make your GUI observe your model via an observer, and have the observable model fire events to the observers in the setters. The former will lead to spaghetti code eventually, as you add more and more direct links between model and view, and thus should only be used for in-house tools and simple programs.

Upvotes: 0

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422310

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.

Upvotes: 18

Related Questions