Compartilhar via


Anonymous Method Part 2 answers

I think the winner is Jerry Pisk.  His final comment I think does the best job of explaining, what I was trying to explain.  Thanks Jerry.  I also partially agree with Jerry's first comment, namely anonymous methods can be confusing and lead to poor readability and general mis-use.  However, I also believe there are some situations where they are cleaner and more readable than other styles of coding, but that's just my opinion.

Now it seems like a few of you were confused by the loop variable i.  Specifically RichB's comment.  In his example, the two snippets are almost identical, they will produce the same output.  Semantically a for loop is treated something like this:


for (init_expression; test_expression; increment_expression){    body;}

{
    init_expression;
    while (test_expression)
    {
        body;
        increment_expression;
    }
}


Since the init_expression is outside of the loop there is only one instance of the loop variable that is shared by all iterations of the loop.  Just to blow your minds and prove that this is really tied to scopes and not really loops here's the same example as my previous post, only rewritten using gotos instead of  fancy loops


delegate void NoArgs();

void SomeMethod(){    NoArgs [] methods = new NoArgs[10];``    int outer = 0;    {        int i = 0;        goto Test_Label;`` Loop_Label:        {        ``    int inner = i;            methods[i] = delegate {                Console.WriteLine("outer = {0}", outer++);                Console.WriteLine("i = {0}", i);                Console.WriteLine("inner = {0}", ++inner);            };            methods[i]();        }``        i++;Test_Label:        if (i < 10)            goto Loop_Label;    }``}


There are 10 instances of inner because the scope that declares inner, is entered 10 times.  There is only one instance of i because the scope that declares i is only entered once (but there's lots of goto's within it).  By simply moving the declaration of inner to the next outer scope then like i, there will only be one instance.  Hopefully once we get these community drops going, you'll be able to try this stuff out yourselves.

--Grant