I want to return generic function as a result of my function in C#.
For example, I want to create a function PopManyBuilder(int n)
which returns a function that will take any List
and return copy of the given List
, but without n last elements.
I tried something like this:
static Func<List<T>, List<T>> PopManyBuilder<T>(int n)
{
return list =>
{
var result = new List<T>(list);
for (int i = 0; i < n; ++i)
{
list.RemoveAt(list.Count - 1);
}
return result;
};
}
static void Main(string[] args)
{
var pop5 = PopManyBuilder<int>(5);
var array = new List<int> {1,2,3,4,5,6,7,8};
var newArray = pop5.Invoke(b);
}
But I can't use built function pop5
on any List<T>
, only on List<int>
.
How can I create a function pop5
for all possible types?