Hey I have an abstract generic type BList<TElement> where TElement : Career. Career is abstract type too.
Given a type T, how do I test if it is a BList type? And how can I cast to the base class? I tried (BList<Career>)object but the compiler was upset. Apparently I can’t write BList<Career> because Career is abstract.
There’s a bit of ambiguity with your question, so I’ll attempt to answer some of the things i think you may be asking…
If you want to check if an instance
Tis a BList you can just useis:If you want to see if a generic type parameter is a
BList<Career>you can usetypeof:But, if you are just wanting to see if it’s any
BList<>, you can use reflection:Now, as far as how do you cast a
BList<TElement>to aBList<Career>? You can’t safely.This has nothing to do with
Careerbeing abstract, it has to do with the fact thatBList<Career>does not inherit fromBList<TElement>even thoughCareerinherits fromTElement.Consider this:
Given those, ask yoruself why does this not work:
See the problem? If we allow you to cast a
List<Cat>to aList<Animal>, then all of the sudden theAdd()method will supportAnimalinstead ofCat, which means you could do this:Clearly, there is no way we should be able to add a
Dogto aList<Cat>. This is why you can’t use aList<Cat>as aList<Animal>even thoughCatinherits fromAnimal.Similar case here.