16

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?

Jack
  • 5,680
  • 10
  • 49
  • 74

3 Answers3

26

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();
    }
)
);
hcb
  • 8,147
  • 1
  • 18
  • 17
  • I see, the Action type. Any differences in using the Action type vs casting? – Jack Oct 13 '11 at 07:27
  • 1
    here is a discussion about action vs methodinvoker: http://stackoverflow.com/questions/1167771/methodinvoker-vs-action-for-control-begininvoke – hcb Oct 13 '11 at 09:57
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.

Brent Arias
  • 29,277
  • 40
  • 133
  • 234
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.

Ryder
  • 341
  • 2
  • 11