MethodInvoke delegate or lambda expression

29.1k Views Asked by At

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?

3

There are 3 best solutions below

2
On BEST ANSWER

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

The two approaches are equivalent. The first is known as an anonymous method, and is an earlier .net 2.0 capability. The lambda should not require a cast.

I would prefer the lambda, because it has more ubiquitous use in modern C#/.net development. The anonymous delegate does not offer anything over the lambda. The lambda allows type inference, which ranges from convenient to necessary in some cases.

0
On

MethodInvoker provides a simple delegate that is used to invoke a method with a void parameter list. This delegate can be used when making calls to a control's Invoke method, or when you need a simple delegate but do not want to define one yourself.

an Action on the other hand can take up to 4 parameters.