Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 823
Jack Avatar asked Oct 13 '11 07:10

Jack


People also ask

Is a lambda expression a delegate?

Lambda expressions are also examples of delegates, which are collections of lines of code that can take inputs and optionally return outputs. We use the type Func<T> to define delegates that return an output, and Action<T> for delegates that will not return an output.

What is the difference lambdas and delegates?

They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences.

Which type of delegate is used to refer to a lambda expression without returning value?

Action<> is used when there is a need to perform an action using the arguments of the delegate. The method it encapsulates does not return a value.

What is delegate in Linq?

Introduction. A delegate is a C# type similar to function pointers in C++. It encapsulates references to one or multiple methods. Func<> is a special kind of Multicast Delegate used frequently with LINQ and Enumerable extensions. Let's have a close look at Func<> delegates.


2 Answers

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();
    }
)
);
like image 115
hcb Avatar answered Sep 21 '22 08:09

hcb


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.

like image 36
Brent Arias Avatar answered Sep 21 '22 08:09

Brent Arias