15

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

2 Answers 2

33

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

Sign up to request clarification or add additional context in comments.

Comments

-2

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

1 Comment

Func<string> (which is what his second example is using) is a function that takes no parameters and returns a string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.