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.
IEntityService<T> where T : IMongoEntity
was changed toIEntityService<out T> where T : IMongoEntity
I think it would work. You are running in to covariance isues – Scott Chamberlain Sep 25 '15 at 16:19IEntityService<T>
has anAdd(T item)
method. (We don't know whether or not it does, but the compiler doesn't care. It could.) Now think what that means for anIEntityService<IMongoEntity>
- you can add any mongo entity to it. Now, can you add aManagementProject
to aSalesService
? Nope... That's why it's invalid. – Jon Skeet Sep 25 '15 at 16:25out
is what tells the compiler that you do not have anyAdd(T item)
calls. – Scott Chamberlain Sep 25 '15 at 16:39