Joe
Joe

Reputation: 3834

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

Upvotes: 15

Views: 14376

Answers (2)

Davi Ruiz
Davi Ruiz

Reputation: 120

You need to know the function definition:

Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

References:

Microsoft

Upvotes: -2

Reed Copsey
Reed Copsey

Reputation: 564413

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

Upvotes: 33

Related Questions