MethodInvoke delegate or lambda expression
Asked Answered
C

3

17

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?

Civilian answered 13/10, 2011 at 7:3 Comment(0)
L
27

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();
    }
)
);
Lotte answered 13/10, 2011 at 7:7 Comment(2)
I see, the Action type. Any differences in using the Action type vs casting?Civilian
here is a discussion about action vs methodinvoker: #1168271Lotte
J
3

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.

Julienne answered 13/10, 2011 at 7:5 Comment(0)
B
2

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.

Barncard answered 14/4, 2012 at 8:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.