J.Doe J.Doe - 12 days ago 8
C# Question

Is it possible to make something like an event handler for when a bool toggles?

say I have a variable

doSomethingWhenTrue
. Right now let's say it's
false
. Now every time it toggles values I want it to execute a function similar to this:

private void someResponseToToggledBool()
{
If(boolInQuestion)
{
//do some stuff
boolInQuestion = false;
}
}


Anyone know how to do that? My (crappy) idea is to make a timer and assign this function to its tick value and throw it on another thread... But there has to be a more direct way than that correct?

Answer

You can use a property

private bool _boolInQuestion;
public bool BoolInQuestion
{
    get { return _boolInQuestion; }
    set
    {
         _boolInQuestion = value;
         //call method to do something
    }
}

In the setter you can also raise an event that's handled by whoever needs to react to the toggle, or even implent INotifyPropertyChanged (https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx)

EDIT

As per your comment, you want this property to be static. You can achieve that by declaring both the field and property as static:

    private static bool _boolInQuestion;
    public static bool BoolInQuestion
    {
        get { return _boolInQuestion; }
        set
        {
            _boolInQuestion = value;
            //call method to do something
        }
    }

but this will require the method being invoked in the setter to be static as well. Alternatively, you can keep the property non-static and implement a Singleton:

public sealed class BoolHolder
{
    private BoolHolder() { }

    private static BoolHolder instance = null;        
    public static BoolHolder Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new BoolHolder();
            }
            return instance;
        }
    }

    private bool _boolInQuestion;
    public bool BoolInQuestion
    {
        get { return _boolInQuestion; }
        set
        {
            _boolInQuestion = value;
            //call method to do something
        }
    }
}

and access it as BoolHolder.Instance.BoolInQuestion