Generics, Constraints and a simple question
I made an Interface IParent,
and a bunch of classes Param<T> where T : IParent, but I'm not able to put List<Param<IParent>> like a generic list and add in it 😦
6 Replies
generic covaraince, is a keyword that might explain this
Covariance only works for interfaces
i.e.
IParam<Parent>
, not Param<IParent>
@cathei thanks for getting back, so basically the reason, i'm working with this interface, is to limit the alllowed types in my generic class
Param<T>
T should only be either String, bool, int64, specific classes etc.
for this reason, I had made IParameterDataType, and wrote wrappers for these primitivies,
Param<T> : where T : IParameterDataType
now, I want to be able to have a List<Param<IParameterDataType>>
Your
Param<T>
needs to be interface instead as IParam<out T>
Then your T can be covariantwow, that fixed it, thanks! i don't get it why it isn't supported in classes tho, but thanks
Even if it supported on classes it may not be as useful as you think, most of generic classes work invariantly (as in T used as both input and output)