I'm having a spot of trouble with generics in C#. I have to store a number of generic objects together but their type parameter differs so I have made a non-generic interface which they implement. What I'm looking for is a way to convert back to the generic version, given a type object. I know I can do it with reflection but I was wondering if there was a better/more elegant solution.
The following code illustrates the problem:
interface ITable
{
public Type Type { get; }
}
class Table<T> : ITable
{
public Type Type { get{ return typeof(T); } }
}
class Program
{
static void Main(string[] args)
{
var tables = new Dictionary<string, ITable>();
... //insert tables
DoStuffWithTable(tables["my table"]); //This doesn't work
}
public static void DoStuffWithTable<T>(Table<T> table)
{
...//Some work
}
}
Is there a clean way for me to invoke the generic DoStuffWithTable
method based on the instance of the Type object I can get from its interface method?