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?
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.
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.
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.
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.
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();
}
)
);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With