Convert lambda to custom delegate

473 Views Asked by At

In an assembly MyLibrary.Common I define a generic delegate type:

namespace MyLibrary.Common {
  public delegate TResult Instruction<in TArgument, out TResult>(
      CancellationToken cancellationToken,
      Action reportProgress,
      TArgument argument);
}

I then reference this assembly in another VS2010 project, by linking to the corresponding DLL.

When I want to create an instance of this type using the following approach, I get the error below:

Instruction<string, bool> instruction =
  (cancellationToken, reportProgress, argument) => SomeOperation(argument);

private static bool SomeOperation(string arg) {
  return false;
}

The error I get on the instruction = ... line is

Cannot convert source type 'lambda expression' to target type 'MyLibrary.Common.Instruction'


When I try to write the application of SomeOperation(argument) as a private static bool SomeOperationWrapped(string argument) and assign that SomeOperationWrapped identifier to my instruction variable, the error I get is

Expected a method with '??? SomeOperationWrapped()' signature


The odd thing is that in another VS2010 project, I did not get any problems assigning a lambda expression to my Instruction<TArgument, TResult variable.

2

There are 2 best solutions below

0
On

It's interesting that you say that you had no such issues in a different VS2010 project. It would be good to see what that code (which works) looks like.

Are both the source project and the consuming project set to target the same .Net Framework version and possibly also using the same Tools version?

Maybe the compiler is having trouble inferring the types - try making the lambda parameters explicitly typed, and/or explicitly casting the lambda to the delegate type:

Instruction<string, bool> instruction = (CancellationToken cancellationToken, Action reportProgress, string argument) => SomeOperation(argument);

Instruction<string, bool> instruction = (Instruction<string, bool>)((CancellationToken cancellationToken, Action reportProgress, string argument) => SomeOperation(argument));
2
On

Inspired by chamila_c's answer, it turned out that opening the troublesome project by itself (and not by opening it's parent solution) cured the problems.
Steps to reproduce fix:

  • open project by itself. VS2010 creates a new (temporary) solution for it.
  • open the project's original solution to continue working on your code

To date, I don't know exactly why this works, but I assume it's some kind of off-the-books "Clean Project" operation.