I'm defining a lambda and calling it, by appending "()", immediately.
Try:
int i = (() => 0) ();
Error:
Error CS0119: Expression denotes a
anonymous method', where a
method group' was expected
Why is that?
In Python, a lambda function is a single-line function declared with no name, which can have any number of arguments, but it can only have one expression. Such a function is capable of behaving similarly to a regular function declared using the Python's def keyword.
A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.
A lambda just does not support being executed. A delegate supports being executed. A lambda expression can be implicitly converted to a delegate type. In case no such conversion is requested there is no "default" delegate type. Since .NET 2 we normally use Action
and Func
for everything but we could use different delegate types.
First convert to a delegate, then execute:
((Func<int>)(() => 0))()
One could argue that C# should default to using Action
and Func
if nothing else was requested. The language does not do that as of C# 5.
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