You need to declare the delegate (a method being a function here, like in JavaScript) using a Func type to use the lambda syntax:
Func<int, int> square = value => value * value;
As @DmitryBychenko pointed out in his answer, we need to specify a type instead of using var
because C# is a strongly typed OOP compiled language, and not loosely-typed interpreted like JavaScript.
Therefore we can call it:
int result = square(2);
But with the latest versions of C#, the compiler issues a warning to use a local method instead:
int square(int value) => value * value;
Lambda syntax is not a type but a language syntax: we cannot "call a lambda" because we cannot call a certain line of code in a method directly unless we call the method itself.
Delegates and Func/Action as well as instance and local methods are types: thus we call a method.
For example the local method as well as the Func delegate lambda style is exactly the same as:
int square(int value)
{
return value * value;
}
There is a little difference between a local delegate or func/action style (anonymous methods) and a local method.
Difference between sending an anonymous function vs. Func/Action to another function with a Delegate parameter?
Local function vs Lambda C# 7.0
Dissecting the local functions in C# 7