Search code examples
c#lambdawindows-phone

Embedded C# lambda expression as function parameter


Does anyone know what problem is with the below piece of code, which cannot compile in VS2013?

GenericCommand.AddHandlerFactory("MyKey", (cmd, action) =>
{
  return (command) =>
  {
    var result = new SuccessResult() { ResultText = "some example text" };
    result.Send(command.Configuration);
  };
});

The prototype of AddHandlerFactory is :

public static void AddHandlerFactory(string key, Func<GenericCommand, Action> handlerFactory)

When compiles in VS2013, it shows

A local variable named command cannot be declared in this scope because it would give a different meaning to command .... ....

and

Delegate System.Func WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action does not take 2 arguments

More detail of the source code is at: https://github.com/Expensify/WindowsPhoneTestFramework/blob/master/Client/AutomationClient/Remote/GenericCommand.cs

EDIT1 rename the first command to cmd, the first error msg is resolved. But it still cannot compile.

The error msg is :

cannot convert lambda expression to delegate type Delegate System.Func WindowsPhoneTestFramework.Client.AutomationClient.Remote.GenericCommand, System.Action because some of the return types in the block are not implicitly convertible to the delegate return type.


Solution

  • You have two parameters sharing the same name :

    • (command, action) => is one action with a param nammed command

    • return (command) => is another action, with another param nammed command

    So you have to rename one of the two param names.

    As @Dirk explained, you return an Action<T> instead of an Action. So you can try this :

    GenericCommand.AddHandlerFactory("MyKey", (cmd, action) =>
    {
      return () =>
      {
        var result = new SuccessResult() { ResultText = "some example text" };
        result.Send(cmd.Configuration);
      };
    });