Reputation: 733
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?
Upvotes: 2
Views: 85
Reputation: 1578
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
Upvotes: 2
Reputation: 3065
use a property
private bool _doSomethingWhenTrue;
public bool doSomethingWhenTrue
{
get
{
return _doSomethingWhenTrue;
}
set
{
_doSomethingWhenTrue = value;
someResponseToToggledBool();
}
}
Upvotes: 1