public void SomeMethod()
{
List<string> someList = LoadList();
if(condition)
{
MethodInvoker invokeThis = delegate {
someList.Remove(0);
};
if(this.InvokeRequired)
{
this.invoke(invokeThis);
}
else
{
invokeThis();
}
}
}
What I dont understand is how does invokeThis gets access to someList. Shouldnt the scope be limited to delegate { .. };.
No, the access shouldn’t be limited to the
delegate { ... }block. This is a large part of the benefit of anonymous functions (anonymous methods and lambda expressions) – they’re able to capture local variables as part of their environment. In this way they implement closures for C#. Note that these really are variables – if you change the value within the delegate, and then access it within the rest of the method again, you’ll see the new value. The variable can live on even after the method has returned, and you can even have multiple “instances” of a local variable – one each time the declaration is logically executed.See section 7.15.5.1 of the C# 4 spec for more details.