C
C#•2w ago
error ♡

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
error ♡
error ♡OP•2w ago
generic covaraince, is a keyword that might explain this
cathei
cathei•2w ago
Covariance only works for interfaces i.e. IParam<Parent>, not Param<IParent>
error ♡
error ♡OP•2w ago
@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>>
cathei
cathei•2w ago
Your Param<T> needs to be interface instead as IParam<out T> Then your T can be covariant
error ♡
error ♡OP•2w ago
wow, that fixed it, thanks! i don't get it why it isn't supported in classes tho, but thanks
cathei
cathei•2w ago
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)

Did you find this page helpful?