I'm trying to create an extension method that takes a Func as a parameter but I'm getting an error. Here's what I got:
public static class MyExtensions
{
public static TResult ModifyString<T, TResult>(this string s, Func<T, TResult> f)
{
return f(s);
}
}
on the return f(s);
line I get an error: Error CS1503 Argument 1: cannot convert from 'string' to 'T'
How can I specify a generic lambda Func with a generic parameter T
and a generic return type TResult
?
As the other answer and comments suggest, you already know the parameter type T
, so you only need to specify TResult
:
public static TResult ModifyString<TResult>(this string s, Func<string, TResult> f)
{
return f(s);
}
or consistently pass T
:
public static TResult Modify<T, TResult>(this T s, Func<T, TResult> f)
{
return f(s);
}