2

I have a C# class which introduce a new custom event type, and allows users add or remove listeners to it. Also I implement a method which revoves all event listeners during dispatch;

    public event EventHandler DataCommited;

    private void DetatchListeners()
    {
        if (DataCommited != null)
        {
            foreach (EventHandler eh in DataCommited.GetInvocationList())
            {
                DataCommited -= eh;
            }
        }
    }

It is possible to implement a method which will be taking DataCommited event as an argument. So, I can unsign a set of events using one method. I tried a lot ways implementing it, but unfortunately failed to do it. I wonder if it is actually possible and how. Thank you!!!

Luis
  • 11,978
  • 3
  • 27
  • 35
Vsevolod
  • 21
  • 2

1 Answers1

2

It is possible to implement a method which will be taking DataCommited event as an argument.

Well, not really. You can take an EventInfo, but that's all. It's important to understand that this statement:

public event EventHandler DataCommited;

actually creates two things:

  • An event, which code in other classes can subscribe to and unsubscribe from
  • A field of type EventHandler, which you can use to call the handlers, or get each one individually.

A simpler implementation of your current code would simply be this:

public event EventHandler DataCommited;

private void DetatchListeners()
{
    DataCommitted = null;
}

Unsubscribing from a field-like event just changes the value of the field, after all.

However, if you have an EventInfo, you don't know how that event is implement. It may be backed directly by a field - it might not be... there's no general way of asking an event for its current handlers, or setting a new list of handlers. All you can do directly with an event is subscribe and unsubscribe.

If you only use field-like events, you could use reflection to find the name of the field and set the value to null. You can't do it in general though.

See my article on delegates and events for more information.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194