1

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?

  • 2
    You are, already doing it, PopManyBuilder Is generic and could be string,double etc without limit. So I dont understand what you really want. – Alen.Toma Nov 25 '20 at 14:04
  • 1
    @Alen.Toma I want to make a type independent function, not only for String, Double, Int or any specified type. – Iaroslav Sviridov Nov 25 '20 at 14:08
  • what is the error? – zahrakhani Nov 25 '20 at 14:19
  • @zahrakhani for example for `List` https://imgur.com/a/jm7bH36 – Iaroslav Sviridov Nov 25 '20 at 14:29
  • @IaroslavSviridov this is because you passed `int` to `PopManyBuilder`. – derloopkat Nov 25 '20 at 14:31
  • @IaroslavSviridov Tried to post but your question was closed. The problem is, in `PopManyBuilder` you are modifying the original list, not the copy you called `result`. When it returns, you get the original list. Solution is to update `result` in the loop e.g. `for (int i = 0; i < n; ++i) { result.RemoveAt(result.Count - 1); }`. That should work with float, etc. For instance `var pop5 = PopManyBuilder(5); var array = new List { 1f, 2f, 3f, 4f, 5f, 6f, 7f, 8f }; var newArray = pop5.Invoke(array);` – derloopkat Nov 25 '20 at 14:33
  • @derloopkat Yeah, you are right, but how to create type independent function like this? When we want to remove an element from an `List` , we don't care what type of element it is. – Iaroslav Sviridov Nov 25 '20 at 14:40
  • You could get type from the input list. However this question is closed. – derloopkat Nov 25 '20 at 14:50
  • 1
    @derloopkat Post a link to something working on dotnetfiddle.net -- what the OP wants isn't possible, per the linked question. So if you can make it work, I'll vote to re-open – canton7 Nov 25 '20 at 14:55

0 Answers0