I have a set of classes and interfaces which have a relatively simple hierarchy, however having things inherit and then having a variable which accepts the base class is not working well. I think the problem is that my dynamic types MUST be where : class and not where : IEntity because these types are used in functions which I have no ability to change.
public interface IB<X, Y>
where X : class, IEntity
where Y : class, IEntity
{
...
}
public abstract class A
{
...
}
public abstract class B<X, Y> : A, IB<X, Y>
where X : class, IEntity
where Y : class, IEntity
{
...
}
public interface IEntity
{
...
}
public class Entity1 : IEntity
{
...
}
public class Entity2 : IEntity
{
...
}
public class C : B<Entity1, Entity2>, IB<Entity1, Entity2>
{
...
}
And then, attempting to use all this in a function…
C c = new C();
IB<IEntity, IEntity> ib = c;
Cannot implicityly or explicity cast this.
How can I get this to work?
Your interface is not covariantly valid. That is to say,
IB<IEntity, IEntity>andIB<Entity1, Entity2>are not the same thing. To fix this, you can use theoutkeyword on the type parameters in the interface definitionAs a secondary point, you need to cascade your constraints to class B
With these changes in place, your assignment of C into ib is legal.
(And as Davy8 correctly points out in the comments, this interface covariance feature requires C# 4+.)