MethodInvoke delegate or lambda expression

Jack picture Jack · Oct 13, 2011 · Viewed 22.9k times · Source

What is the difference between the two?

Invoke((MethodInvoker) delegate {
        checkedListBox1.Items.RemoveAt(i);
        checkedListBox1.Items.Insert(i, temp + validity);
        checkedListBox1.Update();
    }
);

vs

Invoke((MethodInvoker)
    (
        () => 
        {
            checkedListBox1.Items.RemoveAt(i);
            checkedListBox1.Items.Insert(i, temp + validity);
            checkedListBox1.Update();
        }
    )
);

Is there any reason to use the lambda expression? And is (MethodInvoker) casting delegate and lambda into type MethodInvoker? What kind of expression would not require a (MethodInvoker) cast?

Answer

hcb picture hcb · Oct 13, 2011

1) The lambda expression is somewhat shorter and cleaner

2) Yes

3) You could use the Action type, like this:

Invoke(new Action(
    () => 
    {
        checkedListBox1.Items.RemoveAt(i);
        checkedListBox1.Items.Insert(i, temp + validity);
        checkedListBox1.Update();
    }
)
);