Create an event to observe the change of a variable

Let's say that I have:

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

How to create an event handler that fires when booleanValue changes? Is it possible?

+8
c # event-handling microsoft-metro inotifypropertychanged
source share
6 answers

Avoid using public fields, generally in general. Try to keep them as many as possible. You can then use the wrapper property to fire your event. See an 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); 

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

+12
source share

INotifyPropertyChanged is already defined for property change notification.

Wrap the variable in the property and use the INotifyPropertyChanged interface.

+7
source share
  • Change the access to BooleanValue for private access and allow it with only one method for consistency.

  • User event fire in this method

.

 private bool _boolValue; public void ChangeValue(bool value) { _boolValue = value; // Fire your event here } 

Option 2: Set this property and fire the event in the setter

 public bool BoolValue { get { ... } set { _boolValue = value; //Fire Event } } 

Edit: as others have said, INotifyPropertyChanged is the standard .NET way.

+3
source share

Perhaps look at the INotifyPropertyChanged interface. In the future you will come across this again:

MSDN: http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

+2
source share
 CallingClass.BoolChangeEvent += new Action<bool>(AddressOfFunction); 

In your class with a bool property procedure:

 public event Action<bool> BoolChangeEvent; public Boolean booleanValue; public bool someMethod(string value) { // Raise event to signify the bool value has been set. BoolChangeEvent(value); // Do some work in here. booleanValue = true; return booleanValue; } 
+2
source share

No, this is not possible * to receive notification of changes to the value of a variable.

You can achieve almost what you want by making the value an attribute of a certain class and events of fire when you change, as you wish.

*) if your code is a debugger for the process, you can force the CPU to notify you of changes - see data breakpoints in Visual Studio. This will require at least some native code and is more difficult to implement correctly for managed code because of the ability to move objects in memory using GC.

+2
source share

All Articles