Search code examples
c#delegateslambdainvokemethod-invocation

MethodInvoke delegate or lambda expression


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?


Solution

  • 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();
        }
    )
    );