views:

363

answers:

5

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?

+16  A: 

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.

Mehrdad Afshari
thanks Mehrdad.
Rohit
An excellent common technique to do this is the `INotifyPropertyChanged` interface.
Greg D
+1  A: 

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()
{

}
Just a small observation, it would be better to have your call to "MyVariableHasBeenChanged" after you have changed it. That way you can do something with it in the method and you cope with the case of an exception being thrown in the assignment.
Ray Hayes
Definitely better (and probably the only useful way). Thanks.
A: 

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.

JeeBee
+3  A: 

Use Observer pattern. Here's another reference.

this. __curious_geek
can you justify the negative vote please , for observer pattern as as solution to this problem ?
this. __curious_geek
You're correct and the down-voter should hang their head. In its simplest form an observer is the correct pattern, this is indeed what WPF uses, hence the need to also tell WPF 'what' has changed. I'll +1 you to redress.
Ray Hayes
+2  A: 

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.

Alexey Romanov