12

Is it possible to make such code work?:

    private List<Type> Models = new List<Type>()
    {
        typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel)
    };

    foreach (Type model in Models) // in code of my method
    {
        Connection.CreateTable<model>(); // error: 'model' is a variable but is used like a type
    }

Thanks in advance

Makciek
  • 179
  • 1
  • 2
  • 9
  • yes but there is no easy way like this . for performance reason i suggest you write all code for all types you need. i think there is way with reflection but it would be slow and not easy to implement. – M.kazem Akhgary Mar 04 '16 at 19:08
  • 1
    You'd have to use reflection's `MakeGenericMethod`. There's probably a better way to do what you want. But yes you could. – Jonesopolis Mar 04 '16 at 19:10
  • `CreateTable` should work I think. –  Mar 04 '16 at 19:29
  • 1
    @SamedTarıkÇETİN No, it won't work. typeof(model) doesn't actually get resolved until runtime, but the compiler needs to know about the exact type at compile time. – Arian Motamedi Mar 04 '16 at 19:31
  • @PoweredByOrange I see. Thanks for info. –  Mar 04 '16 at 19:38

2 Answers2

7

You won't be able to use the variable as a generic type using the conventional syntax (CreateTable<model>). Without knowing what CreateTable does, you have two options:

  1. Instead of making CreateTable a generic method, have it take the type as a parameter:

    public static void CreateTable(Type modelType)
    {
    }
    
  2. Use Reflection to dynamically invoke the generic method using the desired type:

    var methodInfo = typeof (Connection).GetMethod("CreateTable");
    foreach (Type model in Models)
    {
        var genericMethod = methodInfo.MakeGenericMethod(model);
        genericMethod.Invoke(null, null); // If the method is static OR
        // genericMethod.Invoke(instanceOfConnection, null); if it's not static
    }
    

Note that the reflection way would be slower since the method info won't be resolved until runtime.

Arian Motamedi
  • 7,123
  • 10
  • 42
  • 82
0

You can do it like this,

private List<Type> Models = new List<Type>()
{
    typeof(LineModel), typeof(LineDirectionModel), typeof(BusStopTimeModel), typeof(BusStopNameModel)
};

void SomeMethod()
{
  MethodInfo genericFunction =Connection.GetType().GetMethod("CreateTable");

  foreach (Type model in Models) 
  {
    MethodInfo realFunction = genericFunction.MakeGenericMethod(model);
    var ret = realFunction.Invoke(Connection, new object[] {  });
  }
}
Vikas Nokhwal
  • 113
  • 10