1

Given a generic class definition BaseClass<T>, is it possible to test this condition?

if (myvar is BaseClass<>)

I would like to know if myvar derives from the generic class, but I do not know (or care) what T might be.

I assume the answer is no... my backup plan is to caveman this via myvar.GetType().ToString().Contains("BaseClass<"), or something.

with
  • 306
  • 3
  • 15

2 Answers2

10

Like this:

if (myVar.GetType().IsGenericType
 && myVar.GetType().GetGenericTypeDefinition() == typeof(BaseClass<>))
LukeH
  • 263,068
  • 57
  • 365
  • 409
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 2
    If the questioner really means "derives from" and not "is the exact type", then neither the questioner's suggestion nor this one is correct. The correct solution is to use the above approach inside a loop that checks not only the current type but also all of its base types. – Corey Kosak Jul 22 '11 at 00:11
  • @Corey: Correct. You need to call `GetGenericTypeDefinition()` on each base type before comparing to `typeof(BaseClass<>))` – SLaks Jul 22 '11 at 00:12
  • Cool, didn't know you could `typeof(BaseClass<>)` w/o the `T`. @Corey is also correct, I do need to traverse the hierarchy for a "derives from". Thanks! – with Jul 22 '11 at 00:25
0

I should think SLaks examples addresses your specific question.

I just have to wonder what good does that do you? Without knowing T you can't cast it to anything or access any members.

The other solution is to use a non-generic interface so that you can actually do something with BaseClass. For example:

class BaseClass<T> : IBaseClass {
}

interface IBaseClass {
    public void SomethingUseful();
}

Now you only need the is operator:

if (myVar is IBaseClass)
    ((IBaseClass)myVar).SomethingUseful();
csharptest.net
  • 62,602
  • 11
  • 71
  • 89
  • It's a performance optimization, a.k.a. justifiable cause for bad code :P I can bypass some work if/when the object does _not_ derive from the generic type. An interface would totally work, I figured checking the type directly would be "easier". – with Jul 22 '11 at 00:57