48

I am trying to create a list of a certain type.

I want to use the List notation but all I know is a "System.Type"

The type a have is variable. How can I create a list of a variable type?

I want something similar to this code.

public IList createListOfMyType(Type myType)
{
     return new List<myType>();
}
1
  • 2
    Make sure there is no faulty design, as this reeks as one. Commented Mar 22, 2010 at 15:32

2 Answers 2

69

Something like this should work.

public IList createList(Type myType)
{
    Type genericListType = typeof(List<>).MakeGenericType(myType);
    return (IList)Activator.CreateInstance(genericListType);
}
Sign up to request clarification or add additional context in comments.

2 Comments

I had to fiddle around with this for a bit before I got it working. I'm a total newbie to using Type, so here is a code snippet other people may find helpful where you call this createList method from your Main or some other method: string[] words = {"stuff", "things", "wordz", "misc"}; var shtuff = createList(words.GetType());
I realize this is old, but @Jan, it this one solved your problem it should be marked as answer. @kayleeFrye_onDeck you can also just do typeof(string[])
23

You could use Reflections, here is a sample:

    Type mytype = typeof (int);

    Type listGenericType = typeof (List<>);

    Type list = listGenericType.MakeGenericType(mytype);

    ConstructorInfo ci = list.GetConstructor(new Type[] {});

    List<int> listInt = (List<int>)ci.Invoke(new object[] {});

3 Comments

The problem is that we don't know the myType is typeof(int), so your last statement can't be List<int>, we would like something like Liar<myType>, but of course that can't be done. To create the instance we should use System.Activator.CreateInstance(myType). But then again, the return value if an object of type myType. And you have to use the System.Type to find out about the methods / properties / interfaces etc.
It can be done using generics: List<T> CreateMyList<T>(). Inside of this method you can do: Type myType = typeof(T); and then everything as above. You would be able to use method like this: List<int> list = CreateList<int>()
Downvoted because the solution doesn't fit the problem. The issue is that 'T' isn't known, so even doing CreateMyList<T> isn't valid, because T is is most likely not available.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.