I have a chain of hierarchically nested generic interfaces, which for examples sake look like this:
ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
IEnumerable<TWheels> Wheels { get; set; }
}
IWheels<TBolts>
where TBolts : IBolts
{
IEnumerable<TBolts> Wheels { get; set; }
}
IBolts
{
}
Is this a sensible way of handling these generic interfaces?
It makes defining methods look like this:
public TCar GetCar<TWheels, TBolts>(int id)
where TCar : ICar<TWheels, TBolts>
where TWheels : IWheels<TBolts>
where TBolts : IBolts
{
...
}
Is there any way to reduce this code signature?
Generics in C# should be used very carefully to avoid problems like you've faced. I'd recommend to revise interfaces hierarchy and throw generics away:
interface ICar
{
IEnumerable<IWheel> Wheels { get; set; }
}
interface IWheel
{
IEnumerable<IBolt> Bolts { get; set; }
}
interface IBolt
{
}
Then it would be great to look at use-cases, where those interfaces participate.
May be, there will be very rare cases, when you'll need IR16Wheel instead of IWheel, and type casting will be enough.
May be, it will be enough to pair non-generic interfaces with generic ones:
interface IWheel<TBolt> : IWheel
where TBolt : IBolt
{
IEnumerable<TBolt> Bolts { get; set; }
}
and use non-generics with methods like this:
public ICar GetCar(int id) { }
but also use generics in more specific cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With