How do I unsubscribe an anonymous delegate from an event?
I am unit testing (in NUnit) a method that fires an event, and I am using an
anonymous delegate to subscribe the test method to the event:
// Create order
Order testOrder = new Order();
// Create anonymous delegate to subscribe to DeliveryNeeded
event
testOrder.DeliveryNeeded +=
delegate(object sender, DeliveryNeededEventArgs e)
{
Assert.AreEqual(2, e.OrderItems.Count);
};
The anonymous delegate works fine. At the end of the test method, I want to
unsubscribe from the event. How do I do that with an anonymous delegate?
The obvious possibility:
// Unsubscribe from the DeliveryNeeded event
testOrder.DeliveryNeeded -= delegate(object sender,
DeliveryNeededEventArgs e) { };
But that doesn't appear to work--the event still has a subscriber after that
code executes.
Thanks in advance!
David Veeneman
Foresight Systems
Christof Nordiek - 27 Nov 2007 14:43 GMT
You could not directly assign the delegate to the event but to a variable:
DeliveryNeededEventHandler handler = delegate{....}
testOrder.DeliveryNeeded += handler;
....
testOrder.DeliveryNeeded -= hander;
Christof
> How do I unsubscribe an anonymous delegate from an event?
>
[quoted text clipped - 29 lines]
> David Veeneman
> Foresight Systems
David Veeneman - 27 Nov 2007 15:00 GMT
Great solution--it works like a champ. Thanks!