I'm having some trouble understanding why a cast I'm performing is throwing runtime exceptions stating that it's an illegal cast. I did a bit of research and found this answer, which lead me to the MSDN article Covariance and Contravariance in Generics. However, I'm still a bit confused so if anyone can help clarify it would be greatly appreciated.
Here's the object hiearchy for 2 class types:
IMongoEntity (interface)
| - MongoEntity (abstract)
| | -SalesProject (concrete)
| | -ManagementProject (concrete)
IEntityService<T> where T : IMongoEntity (interface)
| -EntityService<T> where T : IMongoEntity (concrete superclass)
| | - MgmtService : EntityService<ManagementProject> (subclass)
| | - SalesService : EntityService<SalesProject> (subclass)
The two non generic services were only created so I could create some specific methods that only apply to those specific types (predefined lookups into the db essentially).
I then have this line, which throws the InvalidCastException
:
IEntityService<IMongoEntity> service = fromsales ?
(IEntityService<IMongoEntity>)salesService :
(IEntityService<IMongoEntity>)mgmtService;
Since both services are derived from the same interfaces & abstract classes and the type parameters used are derived from the same abstract class, then why is this cast illegal?
NOTE: I have workarounds for this, so I'm not really looking for a solution, but instead I want to understand why this is not allowed.