Search code examples
c#genericsienumerable

returning a generic IEnumerable<T>


I want to have a method that returns any collection type - that implements IEnumerable (?) - (so e.g: List, Stack, Queue, ...)

Furthermore it should return any collection type, of any datatype. so i want this method to be able to return a List<string>, as well as a Stack<int>, as well as a List<double>... etc etc.

 public IEnumerable<T> returnSomething() 
    {
        Stack<int> stackOfInts = new Stack<int>();
        List<string> listOfStrings = new List<string>();
        return stackOfInts;
    }

this is what i've tried so far. this however doesn't work, i get this error:

Cannot implicitly convert type 'System.Collections.Generic.Stack<int>' to 'System.Collections.Generic.IEnumerable<T>'. An explicit conversion exists (are you missing a cast?)

however, if i replace the IEnumerable<T> in the method signature to IEnumerable<int> , i can return any collection of type int. This however means, that now i can't return the ListOfStrings anymore.

How can I resolve this?


Solution

  • You need to add a generic type parameter to your method:

    public IEnumerable<T> ReturnSomething<T>() 
    {
        Stack<T> stackOfT = new Stack<T>();
        return stackOfT;
    }
    

    The type parameter appears after the method name, but before the parameters. It is also possible to have a method with more than one type parameter.

    When you call the method you can specify the type:

    IEnumerable<int> myInts = ReturnSomething<int>();