This post originated from an RSS feed registered with .NET Buzz
by Udi Dahan.
Original Post: Re: Generics, Anonymous Methods, & Delegate inference
Feed Title: Udi Dahan - The Software Simplist
Feed URL: http://feeds.feedburner.com/UdiDahan-TheSoftwareSimplist
Feed Description: I am a software simplist. I make this beast of architecting, analysing, designing, developing, testing, managing, deploying software systems simple.
This blog is about how I do it.
When using plain old event handlers, it is perfectly acceptable to subscribe and unsubscribe by doing the following:
Commands.Open.Activated += new EventHandler<OpenEventArgs>(Open_Activated);
Commands.Open.Activated -= new EventHandler<OpenEventArgs>(Open_Activated);
Even though the delegate that you are removing is a different object than the one you subscribed with, since delegates are immutable they behave like value types so this works. However, with anonymous delegates this is apparently not the case (as my previous post showed). The following code is incorrect, even for the same object 'f':
Considering that anonymous methods are syntactic sugar for regular delegates, and the whole variable promotion is handled by the compiler, it is unclear why anonymous methods behave differently.
Anyway, here's the correct code - courtesy of Ayende Rahien:
private void RouteForm_OnNeedPolyline(object sender, EventArgs e)
{
IRouteForm f = sender as IRouteForm;
if (f == null) return;
EventHandler<OpenEventArgs> openCallback = delegate(object sender, OpenEventArgs e)
{
Polyline p = e.Entity as Polyline;
if (p != null)
f.Polyline = p;
Commands.Open.Activated -= openCallback;
};
Commands.Open.Activated += openCallback;
Commands.New.Activate(this, new NewEventArgs(typeof(Polyline)));
}