C# Anonymous method variable scope problem with IEnumerable<T>

Posted by PaN1C_Showt1Me on Stack Overflow See other posts from Stack Overflow or by PaN1C_Showt1Me
Published on 2010-04-13T09:26:07Z Indexed on 2010/04/13 9:33 UTC
Read the original article Hit count: 400

Hi. I'm trying to iterate through all components and for those who implements ISupportsOpen allow to open a project. The problem is when the anonymous method is called, then the component variable is always the same element (as coming from the outer scope from IEnumerable)

foreach (ISupportsOpen component in something.Site.Container.Components.OfType<ISupportsOpen>())
{
    MyClass m = new MyClass();  
    m.Called += new EventHandler(delegate(object sender, EventArgs e)
    {                           
        if (component.CanOpenProject(..)) component.OpenProject(..);
    });

    itemsList.Add(m);
}

How should it be solved, please?

© Stack Overflow or respective owner

Related posts about c#

Related posts about anonymous-methods