I am trying to implement (C#) an interface method in a class, returning a derived type instead of the base type as defined in the interface:
interface IFacto
Your GetCar
method has to return a BaseCar
in order to implement the interface. As the error says, the class' method's return type must match the interface's method's return type.
There's nothing stopping you creating an instance of MyCar
, then returning that:
BaseCar GetCar()
{
return new MyCar();
}
An alternative, if you want to get the typed version of the new class, is to use generics as per John's answer.
Use Generics
interface IFactory<T> where T: BaseCar
{
T GetCar();
}
class MyFactory : IFactory<MyCar>
{
MyCar GetCar()
{
}
}
class MyCar : BaseCar
{
}
There are 2 ways to accomplish this. You can either use generics or explicitly implement interface members.
Generics
interface IFactory<T> where T: BaseCar
{
T GetCar();
}
class MyFactory : IFactory<MyCar>
{
MyCar GetCar()
{
}
}
Explicitly implemented members
interface IFactory
{
BaseCar GetCar();
}
class MyFactory : IFactory
{
BaseCar IFactory.GetCar()
{
return GetCar();
}
MyCar GetCar()
{
}
}