Hi i am having alot of trouble understanding how I can triger an event when a bool value changes.

I have a very vague understanding that i require a delegate to handle the event ???? and I need to add the event to the event listner with += ????

I do not kow enough about this to understand the tutorials i have looked at, most of which are dealing with custom classes. Please can anyone help.

Thanks

Dani AI

Generated

Both replies here point in the right direction: 's note about delegates and 's publisher/subscriber idea are useful. A cleaner, more testable approach is to expose the bool as a property, compare old vs new in the setter, and raise a typed event that carries old/new values. That keeps the source responsible for detecting changes (no timer/polling), gives subscribers useful context, and makes the behavior predictable.

public class BoolChangedEventArgs : EventArgs
{
    public bool OldValue { get; }
    public bool NewValue { get; }
    public BoolChangedEventArgs(bool oldValue, bool newValue)
    {
        OldValue = oldValue;
        NewValue = newValue;
    }
}

public class Sensor
{
    private bool _isActive;
    public event EventHandler<BoolChangedEventArgs> IsActiveChanged;

    public bool IsActive
    {
        get => _isActive;
        set
        {
            if (_isActive == value) return;
            var previous = _isActive;
            _isActive = value;
            IsActiveChanged?.Invoke(this, new BoolChangedEventArgs(previous, value));
        }
    }
}

Subscriber example:

var sensor = new Sensor();
sensor.IsActiveChanged += (s, e) =>
    Console.WriteLine($"IsActive: {e.OldValue} -> {e.NewValue}");

Practical notes: if the bool may change on background threads and handlers touch UI, marshal back to the UI thread (Control.Invoke/Dispatcher/SynchronizationContext). If you target pre-C#6, capture the handler to a local variable before the null check to avoid race conditions. For data binding scenarios prefer implementing INotifyPropertyChanged instead of a custom event. Unsubscribe when appropriate (or use weak-event patterns in long-lived publisher/subscriber situations) to avoid memory leaks. This pattern is simple, explicit, and easier to unit-test than blind polling.

Recommended Answers

All 2 Replies

This snippet might help : ( at least the delegate part )
http://www.daniweb.com/code/snippet1012.html

A delegate of type function is created. I can let it point to different functions which I can feed to one method. I don't have to use pointers the compiler takes care of that. Isn't that amazing?

In C# events are handled in a fashion where their are "publishers" and "subscribers". the "publisher" must define and fire the event, and all subscribed objects (which can be any object) will handle that event.

Delegates for an event typically accept 2 params, the object that fired the event, and the arguments to be passed to the event handler.

exmpl

public delegate void boolChangeHandler(object sender, EventArgs e);
public event boolChangeHandler boolChanged;

boolChangeHandler is the name of the delegate, sender is the object that fired the event. EventArgs is defined under the System namespace. boolChanged is the name of the event, which is published to the Subscriber

now in the code on the object that raises the event, we can create a private virtual method to fire the event, that will first check to make sure that there are subscribers, and if not. then don't fire the event

protected virtual void OnboolChanged()
            {
                if (boolChanged != null)
                {
                    boolChanged();  // Fire the event!
                }
            }

and now to call the event
just calling

OnboolChanged();

would fire your event in all your subscribers, but as for checking for change in a Boolean value, Im not sure of the best way, But you could use something like this

private bool checkBOOL(bool theBool, bool theHolder)
{
    if(theBool != theHolder)
      {
        OnboolChanged();//fire event
        return theBool;
       }
    else
       {
         return theHolder;
       }
}

and just put a call to that method inside a timers tick event with some stuff to check update the holder variable

//having the actual bool to be checked and a holder bool variable both on a higher scope, in this example declared as myBool, and myHolder.

myHolder = checkBOOL(myBool, myHolder);

remember to initially set the mybool and myholder variables to the same value to keep the event from firing on load.

that code, inside a timer tick, every tick at the set interval would check to see if your current bool value was equal to that value at last check, it it is, then it doesn't change it, but if its not. it fires the event, then sets the holder to the new value to wait for it to happen again.

Best of luck with your application!
Happy Coding!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.