I'm trying to use a dynamic object on a generic class. I've based myself on one of the answers of this thread, that basically suggest the usage of a dynamic type instead of reflection and, as I'd like to increase type safety, I'd rather use the dynamic type approach.
This is the class I have:
public class DataGrid<T>
{
public List<T>? RawData;
public void CreateInstance(T dataMessageType)
{
RawData = new List<T>();
}
public void GetHistoricalData(T dataMessageType)
{
var item = GetDataFromSource(dataMessageType); // ommitted to simplify
RawData?.Add(item);
}
}
Which I'm trying to further use here:
public class MainGrid
{
public void LoadData()
{
dynamic t = GetDataType(); // this method returns a Type. Ommitted to simplify;
var historicalData = new DataGrid<t>(); // Error. See comment 1 below
historicalData.CreateInstance(t); // Error. Comment 2 below
historicalData.GetDataFromSource(t); // Error. Also comment 2 below
}
}
Comment 1: I know this is incorrect, but I'm not sure how this could be done using a dynamic type as opposed to reflection.
Comment 2: when I replace 't' by the Type returned by the (ommitted) GetDataTypecode method the code compiles, but there is a runtime error informing 'The best overloaded method match for ... has some invalid arguments'. I don't see what I'm missing here too...