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!"; };
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.
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.
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.
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();
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
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