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:
(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
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.
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