Search code examples
c#typesgeneric-programming

How to use a Type variable as a Type Parameter in a loop?


I want to do this:

foreach(Type t in Aplicables)
{
    filename = Path.Combine(dataDir, t.Name + "s.txt");
    tempJson = JsonConvert.SerializeObject(DataRef<t>.DataList.ToArray());
    System.IO.File.WriteAllText(filename, tempJson);
}

But I can't.

I understand that it has something to do with compiling. Like the compiler needs to be told explicitly what type is going to be used before run time. That's fine. But I'd prefer to do this in a loop rather than having to type it out manually for each member of "Aplicables".

Is there a way to do that?

BTW

public struct DataRef<T>
{
    public int RefNum;
    public static List<T> DataList = new List<T>();

    public T value
    {
        get
        {
            return DataList[RefNum];
        }
    }

}

Solution

  • You'll need to do something like this:

    foreach (Type t in Aplicables)
    {
        filename = Path.Combine(dataDir, t.Name + "s.txt");
        var prop = typeof(DataRef<>).MakeGenericType(t).GetProperty("DataList");
        var dataList = prop.GetValue(null) as //List<int> or whatever your dataList is;
        tempJson = JsonConvert.SerializeObject(dataList.ToArray());
        System.IO.File.WriteAllText(filename, tempJson);
    }