Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variable as Type [duplicate]

Tags:

c#

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

like image 862
Makciek Avatar asked Mar 04 '16 19:03

Makciek


1 Answers

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.

like image 57
PoweredByOrange Avatar answered Sep 28 '22 06:09

PoweredByOrange