C# Inline lambda evaluation

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, but can not be evaluated like a Func?

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

18
задан Shane Arney 21 January 2011 в 16:58
поделиться