I have several car factories:
HondaFactory, MercedesFactory, ToyotaFactory
All of these factories have a Create() method:
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.