Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Heirarchical nested generic interfaces

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?

like image 259
Elliott Avatar asked Apr 25 '26 17:04

Elliott


1 Answers

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.

like image 183
Dennis Avatar answered Apr 28 '26 06:04

Dennis