Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Inline lambda evaluation

Tags:

c#

lambda

At various times while programming in C# I've found myself in situations where I'd like to define a lambda (or anonymous delegate) and call it in the same line. At this point, the 'cleanest' way I've been able to do this is like this:

bool foo_equals_bar = new Func<String, bool>(str => str.Equals("foo"))("bar");

I would love to be able to do write something like the following instead:

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

Unfortunately, this doesn't seem to work. I would love to know:

  1. Is there a simpler way of writing the line of code above?
  2. What is returned from (str => str.Equals("foo")) such that is can be used to initialize a Func<String, bool>, but can not be evaluated like a Func<String, bool>?

I should point out that I'm working in C# 3 (VS2008), so if a solution only exists in C# 4, please mention that. (I'd still like to know, even if the solution isn't available to me at the moment).

Thanks

like image 257
Shane Arney Avatar asked Jan 21 '11 16:01

Shane Arney


2 Answers

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");

like image 78
Konstantin Oznobihin Avatar answered Sep 23 '22 02:09

Konstantin Oznobihin


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.

like image 21
Adam Rackis Avatar answered Sep 24 '22 02:09

Adam Rackis