I want to do something at runtime with objects based on there type. Depending on the type I need to do different operations so I thought I would create an abstract class like this:
internal abstract class DataOperator<T>
where T : class
{
public abstract void DoSomething(IList<T> data);
}
with multiple concrete implementations like:
class MyClassOperator : DataOperator<MyClass>
{
public override void DoSomething(IList<MyClass> data)
{
throw new NotImplementedException();
}
}
But how would I actually create an instance of the concrete class at runtime?
The problem is that
DataOperator<A>andDataOperator<B>are not assignment compatible. Not even ifAandBare. So, you cannot assign your classes to, sayDataOperator<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.
We create an abstract class that implements it explicitly in order to hide this weakly typed
DoSomethingwhen not called through the interface. We also introduce the generic type parameter.We implement concrete types like this:
These implementations are assignment compatible to our interface. Example:
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.Typeor an enum, etc.Same example as above but with the factory: