I always thought that anonymous functions are as mighty as named functions until I wanted to turn a private named function into a anonymous function because just one method body need to call this function. A trivial example:
public void Init(List<int> numbers, List<string> texts)
{
int n = GetFirst(numbers);
string t = GetFirst(texts);
}
private T GetFirst<T>(List<T> list)
{
return list[0];
}
Desired would be to define something like
GenFunc<T, List<T>, T> getFirst = list => list[0];
and use that instead of the instance method GetFirst
. Using Func
is not possible because the generic parameters have a different semantic. I therefore defined a delegate (the "base" of Func
)
delegate T GetFirstDelegate<T>(List<T> list);
but I can instantiate it only with defined generic parameters e.g.
GetFirstDelegate<string> getFirst = list => list[0];
but not as I wish to with placeholder generic parameters:
GetFirstDelegate<T> getFirst = list => list[0];
This makes me think that anonymous methods are not as mightly as named methods - at least in terms of generic usage - or am I missing something?