Creating and applying lambda in one line in C #

Hope this is not a stupid question, but is there a way to achieve the following in C #?

int y = (x => x * x)(9);

I know I can do this:

delegate int Transformer(int x);
Transformer square = x => x * x;
int y = square(9);

But is there a way to do the same thing more succinctly? If not, is there a good reason why not?

+3
source share
2 answers

You can do it:

int y = ((Func<int,int>)(x => x * x))(9);

or use this expression to create a delegate:

int y = new Func<int,int>(x => x * x)(9);

This is not very useful though ...

(I used it Func<int, int>as an alternative to your delegate Transformerwhen you could use the built-in types of delegates.)

+4
source

Since lambda is not related to the type of delegation, you need to specify the type of delegate when you define lambda, either on the left side or on the right side.

This should do the trick:

int result = new Transformer(x => x * x)(9);

Same thing more succinctly:

int x = 9;
int result = x * x;
+5
source

All Articles