Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a lambda function and execute it immediately

Tags:

c#

lambda

I'm defining a lambda and calling it, by appending "()", immediately.

Try:

int i = (() => 0) ();

Error:

Error CS0119: Expression denotes a anonymous method', where amethod group' was expected

Why is that?

like image 877
SpaceMonkey Avatar asked Jun 14 '14 13:06

SpaceMonkey


People also ask

How do you define a lambda function?

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.

What is lambda function explain with example?

A lambda function is a small anonymous function. A lambda function can take any number of arguments, but can only have one expression.

What is a lambda used for in python?

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.


1 Answers

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.

like image 186
usr Avatar answered Nov 08 '22 12:11

usr