22

I have something like this

Type MyType = Type.GetType(FromSomewhereElse);

var listS = context.GetList<MyType>().ToList();

I would like to get the Type which is MyType in this case and pass it to the Generic Type method GetList

This is the error I am getting:

The type or namespace name 'MyType' could not be found (are you missing a using directive or an assembly reference?)

gdoron
  • 147,333
  • 58
  • 291
  • 367
devendar r mandala
  • 253
  • 1
  • 2
  • 6

3 Answers3

30

You can use reflection and construct your call like this:

Type MyType = Type.GetType(FromSomewhereElse);

var typeOfContext = context.GetType();

var method = typeOfContext.GetMethod("GetList");

var genericMethod = method.MakeGenericMethod(MyType);

genericMethod.Invoke(context, null);

Note that calling methods with reflection will add a huge performance penalty, try to redesign your solution if possible.

Alexander
  • 4,153
  • 1
  • 24
  • 37
  • `new[] { MyType }` can be simply `MyType` since `MakeGenericMethod` accepts `params`. – gdoron May 22 '13 at 18:47
  • Thank you, I have modified solution to include this – Alexander May 22 '13 at 18:48
  • 2
    You can circumvent the performance penalty by ILEmitting a dynamic method. Of course you still take a one-shot penalty, but it's a crux of heavy reflection usage (if you have access to that feature). – Lee Louviere May 22 '13 at 18:59
3

You'll have to use reflection:

var method = context.GetType()
    .GetMethod("GetList").MakeGenericMethod(MyType)

IEnumerable result = (IEnumerable)method.Invoke(context, new object[0]);
List<object> listS = result.Cast<object>().ToList();

However there's no way to use your type instance MyType as a static type variable, so the best you can do is to type the results as object.

Lee
  • 142,018
  • 20
  • 234
  • 287
0

You don't build generics dynamically using type. Generics are filled in with a the name of the class, not a type.

You could use Activator.CreateInstance to create a generic type. You'll have to build the generic type dynamically.

To create a generic type dynamically.

Type listFactoryType = typeof(GenericListFactory<>).MakeGenericType(elementType);
var dynamicGeneric = (IListFactory)Activator.CreateInstance(listFactoryType);

Instead of getting the List using a generic method, you could create a generic class that exposes that method. You could derive from an interface like so.

interface IListFactory
{
   IList GetList();
}

class GenericListFactory<T>
{
   public IList GetList() { return new List<T>(); }
}
Lee Louviere
  • 5,162
  • 30
  • 54