Anthony Nichols
Anthony Nichols

Reputation: 1678

Dynamic List Creation based on given object type in C#

I am fairly certain this is possible, and I am thinking it is easy and I just don't know the right way to ask the question in Google. What I want to do is take pass a type into a method and return back a list of objects of that type. something like this:

public List<T> GetComponentsOfType(Type thisType)
{
    return Components.OfType<thisType>().ToList();
}

which of course doesn't compile because I don't know what I am doing.

Upvotes: 3

Views: 247

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 157116

I guess you want to pass in the type parameter so you can get the typed list:

public List<T> GetComponentsOfType<T>()
{
    return Components.OfType<T>().ToList();
}

Upvotes: 3

Related Questions