tags:

views:

584

answers:

5

Suppose that, in C#, myType is a reference to some Type. Using myType only, is it possible to create a List of objects of myType ?

For example, in the code below, although it is erroneous, I'd like to instantiate via

new List <myType> ( ) .

using System ;
using System.Reflection ;
using System.Collections.Generic ;

class MyClass
    {
    }

class MainClass
    {

    public static void Main ( string [] args )
     {

     Type  myType  =  typeof ( MyClass ) ;

     List < myType >  myList  =  new List < myType > ( ) ;

     }

    }
+6  A: 

You can do so using Reflection:

Type typeList = typeof(List<>);
Type actualType = typeList.MakeGenericType(myType);
object obj = Activator.CreateInstance(actualType);
Andy
Actually, I think you have a slight mistake here. you are creating instance of List<MyClass>, so you should cast to <code>var obj = (List<MyClass>)Activator.CreateInstance(actualType);
Ravadre
This proposed solution refers to "MyClass" -- I want to achieve the solution without referring to "MyClass", but, rather, using "myType", only.
JaysonFix
Substitute `typeof(MyClass)` with `myType`, and you have your solution. Obviously you'll have to get rid of the cast in the third line, though, and use reflection to work with the created list - there's no other way if you don't know the type at compile time.
Pavel Minaev
I updated my answer. That's what I get for not proofreading it before posting.
Andy
Looks as if this will work for me ... thank you, Andy, and thanks to everyone else, too.
JaysonFix
+1  A: 

Is there a reason to use

List<myType>' instead of List`

Essentially you're code wants to store objects whose type is not known at compiletime, in a collection (list).

I'd say, if you were planning on making this production code, either use List or use inheritance and store a list of the base classes.

Alan
A: 

This is not possible because myType is not known at compile time and you can't manipulate this list in your code. You could use reflection though to create an Array.

Darin Dimitrov
+2  A: 

You can use reflection, but since the type of the returned list is not known at compile-time, the code using the returned list must access the members through a loosely-typed interface.

This won't result in faster or maintainable code over just using a List.

The better solution is to create a List<interface> where <interface> is a strongest common interface or base class of all of the types you could put in the list at run-time. At least that way, you aren't having to convert back and forth from object when working with the list members, and you'll have some compile-time validation of the sorts of things you're putting in the list.

richardtallent