The problem is that DataOperator<A> and DataOperator<B> are not assignment compatible. Not even if A and B are. So, you cannot assign your classes to, say DataOperator<object>. Therefore, you will have to treat them individually as non related types.
A way out is to have a non generic base type or interface.
interface IDataOperator
{
public void DoSomething(IList data);
}
We create an abstract class that implements it explicitly in order to hide this weakly typed DoSomething when not called through the interface. We also introduce the generic type parameter.
abstract class DataOperator<T> : IDataOperator
where T : class
{
void IDataOperator.DoSomething(IList data)
{
if (data is IList<T> listT) {
DoSomething(listT);
} else {
throw new ArgumentException("The List is not compatible.", nameof(data));
}
}
abstract public void DoSomething(IList<T> data);
}
We implement concrete types like this:
class DataOperatorA : DataOperator<MyClassA>
{
public override void DoSomething(IList<MyClassA> data)
{
throw new NotImplementedException();
}
}
class DataOperatorB : DataOperator<MyClassB>
{
public override void DoSomething(IList<MyClassB> data)
{
throw new NotImplementedException();
}
}
These implementations are assignment compatible to our interface. Example:
IDataOperator[] operators = { new DataOperatorA(), new DataOperatorB() };
If you want to create different operators depending on other data, you can create a factory class. In this example, we use a string as discriminator, but it could be anything else, like a System.Type or an enum, etc.
static class DataOperator
{
public static IDataOperator Create(string op)
{
return op switch {
"A" => new DataOperatorA(),
"B" => new DataOperatorB(),
_ => throw new ArgumentException("Unknown operator.", "op")
};
}
}
Same example as above but with the factory:
IDataOperator[] operators = { DataOperator.Create("A"), DataOperator.Create("B") };
new MyClassOperator()ornew MyClass()(depending on which class you meant by writing "concrete class"). Not sure where this idea of needing reflection for such things is coming from...