In C# how do I create an extension method that takes a lambda with generic parameters, Func<T, TResult> as a parameter.

422 views Asked by At

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?

2

There are 2 answers

1
Mathias R. Jessen On BEST ANSWER

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);
}
5
gmn On

The problem is you are passing "s" - a string into the func which is declared as taking in type "T".

Change the func to take in a string instead of T, and return a string to make this code work with strings.

public static class MyExtensions
{
    public static string ModifyString(this string s, Func<string, string> f)
    {
        return f(s);
    }
}

Assuming you just want a string result.