Generic classes with an generic interface as a type parameter

F

fj

I have an interface with a single generic type parameter.

[[[[
public interface IDriveable<T> where T : ITransmission { ... }
]]]]

I also have a class that has a type parameter that needs to be of that
generic interface type. The type parameter of the generic interface is
used by this class.

[[[[
public class VehicleFactory<T> where T : /* ??? */
]]]]

There is a problem here with this declaration. I can't put
"IDriveable", because that has no type parameters and doesn't match
the type signature of IDriveable. But I also don't want to put
IDriveable<U> either, because then VehicleFactory has to know what
kind of IDriveable it's getting. I want VehicleFactory to accept any
legal kind of IDriveable, and it has to know what kind of IDriveable
it's getting.

There are a few ways I've seen to get around this. The proposed
solution a coworker had was to use:

[[[[
public class VehicleFactory<T, U> where T : IDriveable<U> where U :
ITransmission
]]]]

But I don't like this, since it's redundant. I have to say the "U"
type twice:

[[[[
var factory = new VehicleFactory<IDriveable<AllWheelDrive>,
AllWheelDrive>();
]]]]

Is there a way to get what I want? Specifically, I'm looking for a
solution in which VehicleFactory<...> has only one type parameter, and
is still able to know the inner type parameter of the IDriveable<T>
type it is given.
 
P

Pavel Minaev

[[[[
public class VehicleFactory<T, U> where T : IDriveable<U> where U :
ITransmission
]]]]

But I don't like this, since it's redundant. I have to say the "U"
type twice:

[[[[
var factory = new VehicleFactory<IDriveable<AllWheelDrive>,
AllWheelDrive>();
]]]]

Is there a way to get what I want? Specifically, I'm looking for a
solution in which VehicleFactory<...> has only one type parameter, and
is still able to know the inner type parameter of the IDriveable<T>
type it is given.

No, unfortunately, that's the way things are in C#. There's no
workaround that would do precisely what you want here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top