I can create extension methods from any type. Once such a type is Func from int, for example.
I want to write extension methods for functions, not the type of return functions.
I can do it in a hacky way:
Func<int> getUserId = () => GetUserId("Email"); int userId = getUserId.Retry(2);
If the Retry function is an extension method defined as:
public static T Retry<T>(this Func<T> func, int maxAttempts) { for (int i = 0; i < maxAttempts; i++) { try { return func(); } catch { } } throw new Exception("Retries failed."); }
What I really want to do:
var userId = (() => GetUserId("Email")).Retry(2);
But the compiler does not combine this function as Func of T.
I know about statics, including in Roslyn, so I could do something like:
Retry(() => GetUserId("Email"), 2);
But itโs harder for me to read. I really want the helper function that I created to be out of the way.
There are other patterns that would give me similar results, such as monodic expressions or using a chain (i.e. converting T to a type of chain that has T inside, and then I write extension methods for Chain T), The problem I'm having I come across this approach, is that you need to start with an expression by clicking on a chain from T, and then end the expression by clicking on T, which is a lot of noise distracting the reader's attention from my business logic.
I know I can use implicit casting in a chain from T to T, but it looks like he is doing magic behind the scenes.
So is it possible to get a link to a function without first executing it, with a small amount of boiler plate code?
End of the day, I would like to write the following for any kind of Func / Action:
var settings = LoadSettingsFromDatabase().Retry(2);