Norf
Norf

Reputation: 35

Cannot convert type of instance to type of interface where instance implements interface

Why Given the following classes

class ParentClass<T>{   }
class ChildClass : IInterface{  }
interface IInterface{   }

Do I get a compile time error 'Cannot convert type' when I try to convert from the type ParentClass<ChildClass> to ParentClass<IInterface>, with the below code.

var concreteGeneric = new ParentClass<ChildClass>();
var interfaceGeneric = (ParentClass<IInterface>)concreteClass;

Upvotes: 1

Views: 391

Answers (2)

Grax32
Grax32

Reputation: 4059

What you need here is called covariance and (as @xanatos mentioned) it is only supported for interfaces. If you add an interface to your ParentClass, you can do a conversion to IParentClass<IInterface> and get the functionality you are looking for.

class ParentClass<T> : IParentClass<T> where T : IInterface { }
class ChildClass : IInterface { }
interface IInterface { }
interface IParentClass<out T> where T : IInterface { }

public void TestMethodX()
{
    var concreteGeneric = new ParentClass<ChildClass>();
    var interfaceGeneric = (IParentClass<IInterface>)concreteGeneric;
}

Upvotes: 1

D4rkTiger
D4rkTiger

Reputation: 362

Try to specify precisely which interface extend T

class ParentClass<T> where T:IInterface {   }

Upvotes: 0

Related Questions