What differences are there between declaring:
GenericClass<T> genericInst = new GenericClass<T>();
and
GenericClass<baseClass> temp = new GenericClass<baseClass>();
Here the GenericClass is defined to be for where T : baseClass
GenericClass contains a generic list
private List<T> vals = new List<T>();
It seems to me, and please correct me if I’m wrong, that you are taking ‘where T : baseClass’ as if it were a default for type
Tto be abaseClass?If so, this is not the case, the specialization
where T : baseClassmeans that the typeTmust bebaseClassor derived frombaseClass(or implement if it were an interface instead of a class).Thus, if you had:
Then you can say:
Or
But you could not say:
Since
intdoes not inherit frombaseClass.The only way to actually use
Tin the instantiation above is if you were actually calling that line of code from within theGenericClass<T>:Or from another context where T is already known to be a sub-class of baseClass.
UPDATE
Based on your comments, it sounds like you’re wondering that if you had:
Whether you could add things derived from baseClass into the list, and the answer is yes-ish. The class
GenericClass<T>could be declared for anyTthat inherits from baseClass. But theList<T>would still be strongly typed to typeT.That is given these:
A
GenericClass<BaseClass>could hold bothBaseClassandSubClassin it’sList<T>sinceTwill beBaseClass.But a
GenericClass<SubClass>will have aList<T>whereTwill beSubClassand thus can only hold items ofSubClassor inheriting from it.