Home > Blockchain >  C# How to instantiate type dynamically in code
C# How to instantiate type dynamically in code

Time:06-15

I would like to know if there is a way to instantiate a generic T type into a true type but dynamically, on execution time.

Here is an example of code:

public enum InventoryType
{
    Car,
    Dog,
    House
    Cat
}

public static class Main{

    private readonly IApiClient _apiClient;
    private readonly IPostgreSQL _postgreSql;

    public Main()
    {
        foreach (var inventoryType in default(InventoryType).ToEnumerable())
        {
            Type type;
            switch (inventoryType)
            {
                case Car:
                    type = typeof(Car);
                    break;
                case Dog:
                    type = typeof(Dog);
                    break;
                case House:
                    type = typeof(House);
                    break;
                case Cat:
                    type = typeof(Cat);
                    break;
                default:
            }

            var listOfJson = _apiClient.GetRawData(inventoryType);
            List<type> data = JsonConvert.DeserializeObject<List<type>>(listOfJson);
            _postgreSql.StoreData<type>(data);
        }
    }
}

How can I convert generic T type as true class object and use it as generic T type? For understand: how can I write _postgreSql.StoreData<Car>(data) instead of _postgreSql.StoreData<T>(data) where Car is an variable ?

CodePudding user response:

the easiest way would be something like this

public Main()
{
    foreach (var inventoryType in default(InventoryType).ToEnumerable())
    {
        switch (inventoryType)
        {
            case Car:
                SaveData<Car>(inventoryType);
                break;
            case Dog:
                SaveData<Dog>(inventoryType);
                break;
            case House:
                SaveData<House>(inventoryType);
                break;
            case Cat:
                SaveData<Cat>(inventoryType);
                break;
            default:
        }
    }
}

private static void SaveData<T>(InventoryType inventoryType)
{
    var listOfJson = _apiClient.GetRawData(inventoryType);
    var data = JsonConvert.DeserializeObject<List<T>>(listOfJson);
    _postgreSql.StoreData(data);
    
}
  • Related