When I use reflection in this case, the created type can be many generic types.
BaseStepHandler<BaseStepDataModel> activator = (BaseStepHandler<BaseStepDataModel>)Activator.CreateInstance(....);
The created instance can be all childs of BaseStepDataModel.
BaseStepHandler<OneDataModel>
OR
BaseStepHandler<TwoDataModel>
OneDataModel and TwoDataModel are extending BaseStepDataModel.
this is the exception that I get:
Unable to cast object of type '....GlobalOnBoardingStepOneHandler' to type '....BaseStepHandler`1[....BaseStepDataModel]'.
this is the declaration if GlobalOnBoardingStepOneHandler.
public class GlobalOnBoardingStepOneHandler : BaseStepHandler<GlobalOnBoardingStepOneDataModel>{}
Problem here is you're expecting contravariance covariance for concrete type generic parameters.
Basically, you won't never achieve your goal using a concrete type, but there's a workaround for this.
You can design a marker interface like this:
public interface IBaseStepHandler<out T> // "out" marks T as covariant
where T : BaseDataModel // Do you have a model base type? ;)
{
// Declare members here
}
Where I say "declare members here", just declare such members which are part of your concrete base class (I'm talking about "BaseStepHandler").
After that, implement this interface in your base class BaseStepHandler.
Now, you can do what you want:
IBaseStepHandler<BaseDataModel> some = new WhateverBaseStepHandlerClass();
// This is possible because T generic parameter is covariant and it can be casted to `BaseDataModel`, or if you don't provide a `T` generic parameter constraint, you could cast it to `IBaseStepHandler<object>` too!
In order to learn more about covariance, follow this link: http://msdn.microsoft.com/en-us/library/ee207183.aspx
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