c# bool.change event

21,321

Solution 1

You should use properties in C#, then you can add any handling you want in the setter (logging, triggering an event, ...)

private Boolean _boolValue
public Boolean BoolValue
{
    get { return _boolValue; }
    set
    {
        _boolValue = value;
        // trigger event (you could even compare the new value to
        // the old one and trigger it when the value really changed)
    }
}

Solution 2

Manually, Yes you can

public delegate void SomeBoolChangedEvent();
public event SomeBoolChangedEvent SomeBoolChanged;

private bool someBool;
public bool SomeBool
{
    get
    {
        return someBool;
    }
    set
    {
        someBool = value;
        if (SomeBoolChanged != null) 
        {
             SomeBoolChanged();
        }
    }   
}

Not sure however if this is what you are looking for.

Solution 3

The important question here is: when a bool what changes?

Since bool is a value type you cannot pass around references to it directly. So it doesn't make sense to talk about anything like a Changed event on bool itself -- if a bool changes, it is replaced by another bool, not modified.

The picture changes if we 're talking about a bool field or property on a reference type. In this case, the accepted practice is to expose the bool as a property (public fields are frowned upon) and use the INotifyPropertyChanged.PropertyChanged event to raise the "changed" notification.

Solution 4

Look into implementing INotifyPropertyChanged. MSDN has got a great How To on the subject

Share:
21,321
brux
Author by

brux

I enjoy tinkering with android and web dev.

Updated on May 06, 2020

Comments

  • brux
    brux about 4 years

    Can I setup an event listener so that when a bool changes a function is called?

  • brux
    brux about 13 years
    hmm I'm lost. Could you provide an example to get me going please?
  • jdehaan
    jdehaan about 13 years
    Done :-) Properties are really good at many things. I would urge you to always use them for public data (instead of members). This makes changes or additions easier and you can specify them in interfaces, which you cannot do for members...