Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / C# / November 2007

Tip: Looking for answers? Try searching our database.

Unsubscribing an anonymous delegate?

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
David Veeneman - 27 Nov 2007 14:32 GMT
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!

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.