I know this goes back to variance in general, but I am not sure how to resolve the issue shown below. I want to have a list of generic sensors and add a specific sensor type to the list, but this generates a compiler error, basically stating that the type TempHumSensor is not compatible with Sensor<Measurement>
namespace ConsoleApp3
{
abstract class Measurement
{
public double Value { get; set; } = 0;
}
class TempHumMeasurement : Measurement
{
public double Temp { get; set; }
public double Hum { get; set; }
public TempHumMeasurement(double t, double h)
{
Value = t;
Temp = t;
Hum = h;
}
}
abstract class Sensor<T> where T : Measurement
{
public List<T> Measurements = new();
}
class TempHumSensor : Sensor<TempHumMeasurement>
{
public TempHumSensor() { }
}
internal class Program
{
static void Main(string[] args)
{
var sensors = new List<Sensor<Measurement>>();
var ths = new TempHumSensor();
sensors.Add(ths);
}
}
}
The issue is with last line of code:
Why is that and how to put it the right way ?
I hope this approach will help you: