0

in javascript we can create an arrow function like this :

let square= (a) => a * a;

and call let directly like this :

square(1, 2); 

is there a solution to do something similar to this using c# ? i tried this but it gives me this error ( the delegate type could not be inferred)

var square = (x) => x * x;
lzaek
  • 200
  • 1
  • 10
  • 3
    No, lambda expressions by themselves do not have a type. – Sweeper Aug 16 '21 at 10:14
  • 1
    You have to put `Func` or `Func` or even `Func`, `Func` as labda's type: `var` is not enough: all these possible types can't be *inferred* from `(x) => x * x;` – Dmitry Bychenko Aug 16 '21 at 10:25
  • 1
    In addition to the "not enough type information" issues others are alluding to, there's also the "is this an `Expression` or a delegate?" problem that has to be solved in converting the lambda into something you can store in a variable. – Damien_The_Unbeliever Aug 16 '21 at 10:28

2 Answers2

2

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

2

The problem of

 var square = (x) => x * x;

is that compiler can't infer the type of square from the right value. It can be

 Func<int, int> square = (x) => x * x;
 Func<int, double> square = (x) => x * x;
 Func<double, double> square = (x) => x * x;
 ...
 // if some MyType implements * operator
 Func<MyType, MyType> square = (x) => x * x;

That's why you have to provide the desired type manually, e.g.

 // We square integer (not double, not decimal) values:
 // we take int and return int 
 Func<int, int> square = (x) => x * x;
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215