AlphaModder
AlphaModder

Reputation: 3386

Return Generic Class

I have two classes:

public class Foo<T>{}

public class Bar
{
    private List<Foo> foos = new List<Foo>();
    public Foo GetFoo(int index)
    {
        return foos[index];
    }
}

However, both the list and method say that i need a type parameter for the Foos i specify, but i just want Foos in general, so i could add a Foo< int >, a Foo< float >, a Foo< Baz > etc. etc. to the list, and then have the method return a Foo with an unknown type. And making GetFoo generic is OK if it helps, but I can't figure out how it would.

Upvotes: 2

Views: 97

Answers (2)

eoldre
eoldre

Reputation: 1087

public abstract class Foo 
{ 
    //general foo logic here
}
public class Foo<T>: Foo 
{ 
    //generic type specific information here
}

public class Bar
{
    private List<Foo> foos = new List<Foo>();
    public Foo GetFoo(int index)
    {
        return foos[index];
    }
}

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564333

You could make Foo<T> derive from a base class (or implement an interface) that is non-generic. You could then return a List<IFoo> with the properties that aren't specific to the type T.

This would allow you to have a single list containing any type of Foo<T>.

Upvotes: 5

Related Questions