I am unable to cast a generic type to another generic type, besides the cast should be valid
What I want to archive is in short (for MyModel
implementing IModel
, and MyImplementation
implementing IImplementation
):
IImplementation<IModel> implementation = new MyImplementation<MyModel>();
Assert.IsNull(implementation as IImplementation<IModel>);
This is a bit confusing, as the type should be valid.
Complete conceptual model:
interface IModel {}
class MyModel : IModel {}
interface IImplementation<TModel> where TModel : IModel { }
class MyImplementation<TModel> : IImplementation<TModel>
where TModel : IModel { }
public void CallRegister()
{
var implementation = new MyImplementation<MyModel>();
var instance = CastModel(implementation);
Assert.IsNotNull(instance); //this assert fails!
}
private object CastModel<TModel>(IImplementation<TModel> implementation) where TModel : IModel
{
return implementation as IImplementation<IModel>;
}
I need this cast to enable me to save multiple IImplementation
s to the same Dictionary<Type, IImplementation<IModel>>
, where the key is obtained by doing typeof(TModel)
.
To do this type safe I don't want to use a Dictionary<Type, object>
.
- Why does the cast fail? Are there additional resources to this? Its a similar question to Invalid Cast of Type Constrained C# Generic, but it is not explained why there just that it does not work.
- What is the best way to archive a functionality similar to the dictionary as explained above if this kind of cast is not possible?