Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a lambda expression be declared and invoked at the same time in C#?

Tags:

c#

lambda

In VB.NET, a lambda expression can be declared and invoked on the same line:

'Output 3 Console.WriteLine((Function(num As Integer) num + 1)(2)) 

Is this possible in C#?

like image 519
tronman Avatar asked Jul 09 '12 15:07

tronman


People also ask

Does C have lambda expression?

No, C doesn't have lambda expressions (or any other way to create closures). This is likely so because C is a low-level language that avoids features that might have bad performance and/or make the language or run-time system more complex.

What is the correct statement about lambda expression?

What is the correct statement about lambda expression? Explanation: Return type in lambda expression can be ignored in some cases as the compiler will itself figure that out but not in all cases. Lambda expression is used to define small functions, not large functions.

Can a lambda statement have more than one statement?

The body of a statement lambda can consist of any number of statements; however, in practice there are typically no more than two or three.

What is the correct syntax for lambda expression in C++11?

Lambdas can both capture variables and accept input parameters. A parameter list (lambda declarator in the Standard syntax) is optional and in most aspects resembles the parameter list for a function. auto y = [] (int first, int second) { return first + second; };


2 Answers

You have to tell the compiler a specific delegate type. For example, you could cast the lambda expression:

Console.WriteLine(((Func<int, int>)(x => x + 1))(2)); 

EDIT: Or yes, you can use a delegate creation expression as per Servy's answer:

Console.WriteLine(new Func<int, int>(i => i + 1)(2)); 

Note that this isn't really a normal constructor call - it's special syntax for delegate creation which looks like a regular constructor call. Still clever though :)

You can make it slightly cleaner with a helper class:

public static class Functions {     public static Func<T> Of<T>(Func<T> input)     {         return input;     }      public static Func<T1, TResult> Of<T1, TResult>         (Func<T1, TResult> input)     {         return input;     }      public static Func<T1, T2, TResult> Of<T1, T2, TResult>         (Func<T1, T2, TResult> input)     {         return input;     } } 

... then:

Console.WriteLine(Functions.Of<int, int>(x => x + 1)(2)); 

Or:

Console.WriteLine(Functions.Of((int x) => x + 1)(2)); 
like image 128
Jon Skeet Avatar answered Oct 16 '22 04:10

Jon Skeet


Console.WriteLine(new Func<int, int>(i => i + 1)(2)); 

Uses a few less parentheses to use the Func's constructor than a cast.

like image 45
Servy Avatar answered Oct 16 '22 05:10

Servy