I am trying to create an attribute in a list that takes different types. This is my class:
public class ChartData
{
public string id { get; set; }
public List<dynamic> data { get; set; }
public ChartData()
{
}
public ChartData(string id, List<DateTime?> data)
{
this.id = id;
this.data = data;
}
}
public ChartData(string id, List<float?> data)
{
this.id = id;
this.data = data;
}
public ChartData(string id, List<int?> data)
{
this.id = id;
this.data = data;
}
In the code I use the data
list to store DateTime?
, float?
or int?
data. What do I do to be able to store these different types in one class attribute?
I am getting the error:
Argument 2: cannot convert from 'System.Collections.Generic.List<System.DateTime?>' to 'System.Collections.Generic.List<dynamic>'
I would recommend using Generics if you know the type prior to instantiation
public class ChartData
{
public string id { get; set; }
}
public class ChartData<T> : ChartData
{
public List<T> data { get; set; }
public ChartData()
{
}
public ChartData(string id, List<T> data)
{
this.id = id;
this.data = data;
}
}
Usage:
ChartData<int> intData = new ChartData<int>("ID1", new List<int>());
ChartData<DateTime> dateData = new ChartData<DateTime>("ID1", new List<DateTime>());
ChartData<float> floatData = new ChartData<float>("ID1", new List<float>());
List<ChartData> list = new List<ChartData>() {
intData,
dateData,
floatData
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With