Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an event to watch for a change of variable

Let's just say that I have:

public Boolean booleanValue;

public bool someMethod(string value)
{
   // Do some work in here.
   return booleanValue = true;
}

How can I create an event handler that fires up when the booleanValue has changed? Is it possible?

like image 997
Arrow Avatar asked Jan 07 '13 04:01

Arrow


2 Answers

Avoid using public fields as a rule in general. Try to keep them private as much as you can. Then, you can use a wrapper property firing your event. See the example:

class Foo
{
    Boolean _booleanValue;

    public bool BooleanValue
    {
        get { return _booleanValue; }
        set
        {
            _booleanValue = value;
            if (ValueChanged != null) ValueChanged(value);
        }
    }

    public event ValueChangedEventHandler ValueChanged;
}

delegate void ValueChangedEventHandler(bool value);

That is one simple, "native" way to achieve what you need. There are other ways, even offered by the .NET Framework, but the above approach is just an example.

like image 78
Mir Avatar answered Nov 03 '22 00:11

Mir


INotifyPropertyChanged is already defined to notify if property is changed.

Wrap your variable in property and use INotifyPropertyChanged interface.

like image 38
Tilak Avatar answered Nov 02 '22 23:11

Tilak