Is there a way to execute a lambda expression immediately after its definition?
In other words (Invalid C# code):
For my own projects I've sometimes written a tiny reusable helper function to make the syntax for an immediately invoked lambda look shorter. This 'Inv' was inspired by the similar 'fun' function in the LanguageExt library.
// Helper utility functions
public static void Inv(Action a) => a();
public static T Inv(Func f) => f();
private static void TestMethod()
{
// Action example
Inv(() => Console.WriteLine("Hello World!"));
// Func example with no parameters
bool result = Inv(() =>
{
if (1 == 1)
return true;
else
return false;
});
}
You could also extend this with a few other overloads to make it so you could pass in parameters, but these look a bit more cumbersome syntax wise and may not be as helpful.
public static Func Inv(Func f) => f;
public static Func Inv(Func f) => f;
string printNumber = Inv((int number) => $"This is the number {number}")(5);
int addedNumbers = Inv((int x, int y) => x + y)(5, 6);