Extension method for a function
Per this question, I think the answer is "no".
I would advise you go with a static include of Retry
, as you suggested:
Retry(() => GetUserId("Email"), 2);
It makes intent clear, it's uncomplicated, it's readable enough, and it's idiomatic C#.
An idea that I don't like:
If you were willing to reverse your method arguments, the following would work (but I think most people would think it's pretty awful):
public static T AttemptsAt<T>(this int maxAttempts, Func<T> func)
{
for (int i = 0; i < maxAttempts; i++)
{
try
{
return func();
}
catch
{
}
}
throw new Exception("Retries failed.");
}
Usage:
var userId = 2.AttemptsAt(() => GetUserId("Email"));
The problem is that the member method cannot implicitly cast itself to a Func - which to me seems odd, but maybe there is a good explanation :).
Anyway here is how i would call a Func extension:
var userId = ((Func<int>)GetUserId("Email")).Retry(2);
Of course if you need a one-liner, you will have to cast explicitly to the desired delegate type:
var userId = ((Func<int>)(() => GetUserId("Email"))).Retry(2);