1

I just started working on a project with an existing code base. While looking over the project, I found an odd lambda that I'm trying to understand.

Here's the code:

SomeFunction(x => () => new Y());

I don't understand...

  • why there are two => operators in the callback.
  • what is the purpose of the ().

For reference, here is the method signature of SomeFunction:

ISomeInterface<T> SomeFunction(Func<IXInterface, T> method);
Luke Willis
  • 8,429
  • 4
  • 46
  • 79

1 Answers1

2

The first lambda is returning a second lambda (a function) that returns a new object, in this case of type T. Recall that functions (i.e. delegates) are first-class objects in their own right.

In an ordinary lambda function, there is a lambda parameter that "encloses" the outer scope, as in this predicate:

x => x.SomeMember == true;

The () is simply a placeholder that says "I don't require a lambda parameter here, since I don't need to refer to the outer scope." (x) and (x, y) are also valid forms, so the () just means "no lambda parameters specified."

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • I'd love to see a practical example. – TaW Jul 23 '14 at 21:13
  • 1
    @TaW: It's basically a [Higher-order function](http://en.wikipedia.org/wiki/Higher-order_function). See http://stackoverflow.com/q/5792769 and http://stackoverflow.com/questions/10443285 for some examples of higher-ordered functions. – Robert Harvey Jul 23 '14 at 21:14
  • 1
    Okay, I think I get it now. Could the author also have said `x => (() => y)` to mean the same thing? – Luke Willis Jul 23 '14 at 21:44