Unsubscribing an anonymous delegate?

D

David Veeneman

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
 
C

Christof Nordiek

You could not directly assign the delegate to the event but to a variable:

DeliveryNeededEventHandler handler = delegate{....}
testOrder.DeliveryNeeded += handler;
.....
testOrder.DeliveryNeeded -= hander;

Christof
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top