C# Inline lambda evaluation

You would need a set of helper methods to make compiler infer lambda types, e.g.:


public static class Functional
{
    public static Func<TResult> Lambda<TResult>(Func<TResult> func)
    {
        return func;
    }

    public static Func<T, TResult> Lambda<T, TResult>(Func<T, TResult> func)
    {
        return func;
    }

    public static Func<T1, T2, TResult> Lambda<T1, T2, TResult>(Func<T1, T2, TResult> func)
    {
        return func;
    }
}

Now you can write:


bool foo_equals_bar = Functional.Lambda(str => str.Equals("foo"))("bar");


str => str == "A" 

is the same as

delegate (string str) { return str == "A";};

So no, there's no way to get just the lambda, since the compiler wouldn't know what type str is if you just said

bool result = (str => str == "A")("B");

EDIT:

Yes, you can add types to lambda expressions, like (string str) => str == "A"; but still, they can't be implicit for some reason. Not sure why. Thanks for the comment, Yuriy.


What is returned from (str => str.Equals("foo")) such that is can be used to initialize a Func, but can not be evaluated like a Func?

Just using built-in types, there's:

Expression<Func<string, bool>> a = str => str.Equals("foo");
Expression<Predicate<string>> b = str => str.Equals("foo");
Expression<Action<string>> c = str => str.Equals("foo");
Func<string, bool> a1 = str => str.Equals("foo");
Predicate<string> b1 = str => str.Equals("foo");
Action<string> c1 = str => str.Equals("foo");

All of which are valid interpretations of the lambda expression. That's just the built-in types that I can think of off the top of my head. There's also any delegate that matches the signature.

Tags:

C#

Lambda