15

I am looking to create a List, where the type of T is several unrelated classes (with the same constructor arguments) that I know through reflection.

    DataBase = new ArrayList();
    foreach (Type T in Types)
    {
        DataBase.Add(new List<T>);
    }

Unfortunately, Visual Studio says that 'The type or namespace T could not be found'. Is there some way I can implement this, or cast a List to type T? Thanks, Peter

3
  • 1
    Use the dynamic keyword, perhaps? Assuming the right version of .NET... Commented Jan 20, 2012 at 0:32
  • 1
    don't use ArrayList, worst case just use List<object> if you must Commented Jan 20, 2012 at 0:33
  • @BrokenGlass, I will probably do that, but it is not the ArrayList that is the issue, it is the creation of the List with runtime Type. Commented Jan 20, 2012 at 0:40

3 Answers 3

26

You can use reflection:

List<object> database = new List<object>();
foreach (Type t in Types)
{
   var listType = typeof(List<>).MakeGenericType(t);
   database.Add(Activator.CreateInstance(listType));
}
Sign up to request clarification or add additional context in comments.

2 Comments

That works. But creating the List object is just a small part of problem. He'll also have to add elements to it. And worse, much worse, read them. That code won't know the element type either. An ORM is indicated here, given the word "database".
That works to create the object, but it returns an object. I got that far, but I'm having trouble casting that object as a List<T>. I could of course use "as List<T>" if I knew T, but since that's not defined until runtime I'm not sure how to make it work.
0

You're confusing types and the System.Type class for Generic Type Parameters, here is the code to implement it the way you want:

var lt = typeof(List<>);
foreach (Type T in Types)
{
    var l = Activator.CreateInstance(lt.MakeGenericType(T));
    DataBase.Add(l);
}

Comments

0

You could... use List<object> (if you know that your type is a reference type, or boxing is acceptable); or create a List via reflection.

Comments

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.