Reputation: 10125
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#?
Upvotes: 26
Views: 1582
Reputation: 203828
Console.WriteLine(new Func<int, int>(i => i + 1)(2));
Uses a few less parentheses to use the Func
's constructor than a cast.
Upvotes: 33
Reputation: 1501926
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));
Upvotes: 44
Reputation: 4901
Kind or, you would have to use the Func object :
var square = new Func<double, double>(d => d*d)(2);
Console.WriteLine(square);
Upvotes: 1
Reputation: 16613
Yes, though it's messy:
Console.WriteLine(((Func<int, int>) (num => num + 1))(2));
Upvotes: 14