Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert delegate R Function<T,R>(T t) to Func<T,R>?

Tags:

c#

delegates

func

I've got legacy code that defined the following helper

public delegate R Function<T, R>(T t);

But I want to supply a Func<T,TResult>

casting attempts fail to compile

Cannot convert type 'System.Func<T,TResult>' to 'Rhino.Mocks.Function<T,TResult>'

Is there a way that not only compiles, but functions at runtime?

like image 651
Maslow Avatar asked Feb 22 '12 22:02

Maslow


1 Answers

The problem is you are trying to combine two different delegate types: Func<T, TResult> and Function<T, TResult>. Even though they have the same signature they are different, and hence incompatible, types.

Use a lambda to create a conversion layer between the two.

Func<T, TResult> func = ...;
TheMethod(x => func(x));
like image 99
JaredPar Avatar answered Sep 20 '22 16:09

JaredPar