I have a an extension class that extends Func<T, TResult>
whose signature looks like this:
public static ITryAndReturnValue<TResult> Try<T, TResult>(this Func<T, TResult> func, T arg, int retries)
I can implement it on a method by casting the method to Func<T, TResult>
like so...
Func<string, string> func = request.DownloadString;
string response = func.Try(urlA, 3);
But what I really want to do is this:
string response = request.DownloadString.Try(urlA, 3);
But I get this compile time error.
CS0119 'WebClient.DownloadString(string)' is a method, which is not valid in the given context
Is there anything I can do to get my extension method to work like I want it to?
No, you can't call an extension method on a method group or on an anonymous function.
Section 7.6.5.2 of the C# specification requires that:
An implicit identity, reference or boxing conversion exists from expr to the type of the first parameter of Mj.
(Where expr is the expression you're trying to call the extension method on, and Mj is the extension method itself.)
A method group conversion (the conversion which allows you to write Func<string, string> func = request.DownloadString;
) is not an identity, reference or boxing conversion. It's a separate kind of conversion (section 6.6 of the spec).
See more on this question at Stackoverflow