Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reverse the order of a multicast delegate event?

Tags:

c#

events

When you subscribe to an event in .NET, the subscription is added to a multicast delegate. When the event is fired, the delegates are called in the order they were subscribed.

I'd like to override the subscription somehow, so that the subscriptions are actually fired in the reverse order. Can this be done, and how?

I think something like this might be what I need?:

public event MyReversedEvent
{
    add { /* magic! */ }
    remove { /* magic! */ }
}
like image 616
Neil Barnwell Avatar asked Jun 09 '10 22:06

Neil Barnwell


1 Answers

You don't need any magic; you just need to reverse the addition.
Writing delegate1 + delegate2 returns a new delegate containing the method(s) in delegate1 followed by the methods in delegate2.

For example:

private EventHandler myReversedEventField;
public event EventHandler MyReversedEvent
{
    add { myReversedEventField = value + myReversedEventField; }
    remove { myReversedEventField -= value; }
}

You don't need any magic in the remove handler, unless you want to remove the last occurrence of that handler instead of the first. (In case the same handler was added twice)

like image 192
SLaks Avatar answered Oct 22 '22 14:10

SLaks