How to use a generic type passing the type parameter in a dynamic way?

  • Thread starter Néstor Sánchez A.
  • Start date
N

Néstor Sánchez A.

Hi,
is there a way, maybe using reflection, to use a generic class passing the
type parameter dynamicly (not kwnowing the exact type at compile time)?
I tried the next example, but doesn't work:

public abstract class Vehicle
{ ... }

public class Aircraft : Vehicle
{ ... }

public class SimpleList<AType> where AType:Vehicle
{
....
}

call:
Aircraft Boeing747 = new Aircraft();
SimpleList<typeof(Aircraft)> TheList = new
SimpleList<Boeing747.GetType()>();
....

Thanks,


Néstor.
 
D

Dustin Campbell

is there a way, maybe using reflection, to use a generic class passing
the
type parameter dynamicly (not kwnowing the exact type at compile
time)?
I tried the next example, but doesn't work:
public abstract class Vehicle
{ ... }
public class Aircraft : Vehicle
{ ... }
public class SimpleList<AType> where AType:Vehicle
{
...
}
call:
Aircraft Boeing747 = new Aircraft();
SimpleList<typeof(Aircraft)> TheList = new
SimpleList<Boeing747.GetType()>();
...
Thanks,

The example that you presented doesn't make much sense (since you obviously
know that you're dealing with an Aircraft). However, you can use reflection
to create a generic type using a System.Type as the generic type argument:

Aircraft boeing747 = new Aircraft();

Type simpleListType = typeof(SimpleList<>);
Type boeingListType = simpleListType.MakeGenericType(boeing747.GetType());

object theList = Activator.CreateInstance(boeingListType);

However, if you have to write code like that, you probably aren't using generics
in a way that makes sense. You might want to rethink your design.

Best Regards,
Dustin Campbell
Developer Express Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top