Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous functions with no input parameters

I'm trying to figure out C#'s syntax for anonymous functions, and something isn't making sense to me. Why is this valid

 Func<string, string> f = x => { return "Hello, world!"; };

but this isn't?

 Func<string> g = { return "Hello, world!"; };
like image 573
Joe Avatar asked May 16 '13 20:05

Joe


People also ask

Can anonymous functions have parameters?

An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.

Which function is an anonymous function that is defined without a name?

In Python, an anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions.

Can anonymous functions be called with arguments?

Summary. Anonymous functions are functions without names. Anonymous functions can be used as an argument to other functions or as an immediately invoked function execution.

What are anonymous functions give example?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();


1 Answers

The second still requires the lambda syntax:

Func<string> g = () => { return "Hello, world!"; }; 

In the first, you're effectively writing:

Func<string, string> f = (x) => { return "Hello, world!"; };

But C# will let you leave off the () when defining a lambda if there is only a single argument, letting you write x => instead. When there are no arguments, you must include the ().

This is specified in section 7.15 of the C# language specification:

In an anonymous function with a single, implicitly typed parameter, the parentheses may be omitted from the parameter list. In other words, an anonymous function of the form

( param ) => expr

can be abbreviated to

param => expr

like image 67
Reed Copsey Avatar answered Sep 27 '22 23:09

Reed Copsey