4

If I have an interface with a method that returns a collection of something, is it possible to return an implementation of the collection type instead?

For example:

public interface IVehicle
{
    IEnumerable<Part> GetParts(int id);
}

public class Car : IVehicle
{
    List<Part> GetParts(int id)
    {
        //return list of car parts
    }
}

public class Train : IVehicle
{
    IEnumerable<Part> GetParts(int id)
    {
        //return IEnumerable of train parts
    }
}

If not, why not?

At least to me, this makes sense.

Jessica
  • 1,621
  • 2
  • 18
  • 34

2 Answers2

5

You are of course free to return any implementation of an IEnumerable<Part> as an implementation detail of your GetParts method (e.g. Train may return a List<Part> easily). But the method signatures have to match exactly between an interface definition and a class's implementation of that method.

Here (unlike e.g. overloading) the method signature includes the return type of the method. So no, you cannot write Car as shown or anything similar. You are of course free to have a GetParts method that does return a List<Part> but that will not satisfy the interface requirement - which you may choose to provide an explicit implementation for instead:

public class Car : IVehicle
{
    List<Part> GetParts(int id)
    {
        //return list of car parts
    }
    IEnumerable<Part> IVehicle.GetParts(int id) => this.GetParts(id);
}
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
1

No, C# does not support covariance for inherited methods return type.

Does C# support return type covariance?