GPGVM
GPGVM

Reputation: 5619

Argument Type Not assignable using Lambda parameter

I want to apologize in advance for not connecting the dots to understand the big picture.

This method is a violation of DRY and has a common use 3rd party library that might normally be called like:

ThirdLibrary.DoWork(x => x.Blah....);

In trying to refactor this method I wanted this line and some others near it extracted to a separate method....but I needed to pass in the lambda and Google led me to here and here.

My difficulty is translating to my exact situation with a third party library.

The third party metadata shows it is expecting:

public IDoWork<T> DoWork(Expression<Action<T>> expression);

I'm stumbling on how to parameterize this for my method.

public void RepoDoWork(Action<ICustomerRepository> doworkrule)
{
   ThirdLIbrary.DoWork(doworkrule);
}

This produces the error Argument type is not assignable to parameter type.

Thank you for your assistance in helping me understand how to pass lambdas correctly.

Upvotes: 0

Views: 1616

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Method asks for Expression<...> and you try to pass delegate - there is no useful conversion so that would fail.

To fix you should pass proper Expression to your helper and that to the third party method.

You can try to wrap delegate into expression but in most cases it will not produce useful results at run time. Usually when method takes an expression it means it will deconstruct expression in some way and build logic based on it. Common examples are LINQ-to-SQL constructing SQL queries based on lambdas based to Queryable.Where(...) calls or Moq framework using expressions for setting up method mocks.

Upvotes: 1

Related Questions