Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if Type derives from an abstract base generic type?

Tags:

c#

.net

types

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.

like image 970
Colonel Panic Avatar asked Jan 15 '23 11:01

Colonel Panic


1 Answers

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 T is a BList you can just use is:

if (someInstance is BList<Career>)
{
...
}

If you want to see if a generic type parameter is a BList<Career> you can use typeof:

if (typeof(T) == typeof(BList<Career>)
{
...
}

But, if you are just wanting to see if it's any BList<>, you can use reflection:

var t = typeof(T);  // or someInstance.GetType() if you have an instance

if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(BList<>))
{
    ...
}

Now, as far as how do you cast a BList<TElement> to a BList<Career>? You can't safely.

This has nothing to do with Career being abstract, it has to do with the fact that BList<Career> does not inherit from BList<TElement> even though Career inherits from TElement.

Consider this:

public class Animal { }

public class Dog : Animal { }

public class Cat : Animal { }

Given those, ask yoruself why does this not work:

List<Animal> animals = new List<Cat>();

See the problem? If we allow you to cast a List<Cat> to a List<Animal>, then all of the sudden the Add() method will support Animal instead of Cat, which means you could do this:

animals.Add(new Dog());

Clearly, there is no way we should be able to add a Dog to a List<Cat>. This is why you can't use a List<Cat> as a List<Animal> even though Cat inherits from Animal.

Similar case here.

like image 168
James Michael Hare Avatar answered Feb 18 '23 03:02

James Michael Hare