returning a generic IEnumerable<T>
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>();
The trick is to declare <T>
right, if you define generic <T>
, then you have to stick to it in your methods, so if you have IEnumerable<T>
then elsewhere in your method you must use <T>
and not <int>
or any other type.
It is only latter when you actually use you generic type you substitute generic <T>
for a real type.
See a sample
class Foo<T>
{
public IEnumerable<T> GetList()
{
return new List<T>();
}
public IEnumerable<T> GetStack()
{
return new Stack<T>();
}
}
class Program
{
static void Main(string[] args)
{
Foo<int> foo = new Foo<int>();
IEnumerable<int> list = foo.GetList();
IEnumerable<int> stack = foo.GetStack();
Foo<string> foo1 = new Foo<string>();
IEnumerable<string> list1 = foo1.GetList();
IEnumerable<string> stack1 = foo1.GetStack();
}
}
public IEnumerable<T> returnSomething()
{
Stack<int> stackOfInts = new Stack<int>();
return (IEnumerable<T>) stackOfInts;
}