Showing posts with label anonymous delegates. Show all posts
Showing posts with label anonymous delegates. Show all posts

May 26, 2010

Beware of using anonymous delegates for event handlers

First found a description of this issue here
There is a problem unsubscribing to an event
Check out the following code:
EventHandler onXXX =
 delegate(object sender, XXXEventArgs e)
 {
  onXXXCallCount++;
  xxxs.Add(e.LastXXX);
 };
... 
m_YYY.OnXXX += onXXX;
...
// The anonymous event handler stays on the event handler until removed
// or the parent object is disposed of!
m_YYY.OnXXX -= onXXX;

February 2, 2008

Anonymous Delegates And Iterators

c# 2.0 Iterators
Using anonymous delegates

This code: (Note how an anonymous method can access local variables!)
...
XXX mainXXX = ...
...
xxxList.RemoveAll(
    delegate(XXX xxx)
    {
        return xxx.Id == mainXXX.Id; 
    }
);
Does the same as this:
List entriesToRemove = new List();
foreach (XXX xxx in xxxList)
{
    if (xxx.Id == mainXXX.Id)
    {
        entriesToRemove.Add(xxx);
    }
}
foreach (XXX xxx in entriesToRemove)
{
    xxxList.Remove(userToRemove);
}