Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to construct an interface over types which contain different signatures, but with params all corresponding to the same type

I have several car factories:

HondaFactory, MercedesFactory, ToyotaFactory

All of these factories have a Create() method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Honda Create(HondaParts parts);
Mercedes Create(MercedesParts parts);
Toyota Create(ToyotaParts parts);

All return types implement ICar, and all parts implement ICarParts.

I have a class above all this which, when given a factory type and an ICarParts, wants to simply call Create() on the factory without an if/else/if/else statement on the type.

I went to create an ICarFactory and give it an interface of:

ICar Create(ICarParts parts)

But then I got stuck, as of course each factory has a different signature, even though all of the parameters comply with the ICarParts type. Is there any way to achieve what I’m after?

>Solution :

Use generics

abstract class Factory<TParts> where TParts : ICarParts 
{
    public abstract ICar Create(TParts parts);
}

class HondaFactory : Factory<HondaParts>
{
    public override ICar Create(HondaParts parts)
    {
        ...
    }
}

... other factories

But as always with generics there are limits. E.g., you cannot create a List<Factory<?>> containing different types of factories. The different types of factories are not assignment compatible.

Since C# 9.0 (and .NET 5.0 runtime, I think) you can use covariant return types :

    public override Honda Create(HondaParts parts)
    {
        ...
    }

assuming public class Honda : ICar.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading