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#?
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? 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.
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.
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; };
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));
Console.WriteLine(new Func<int, int>(i => i + 1)(2));
Uses a few less parentheses to use the Func
's constructor than a cast.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With