views:

191

answers:

2

How can I recognize (.NET 2) a generic class?

Class A(Of T)
End Class

' not work '
If TypeOf myObject Is A Then

?

+2  A: 

If c# it would be like this:

public class A<T>
{
}

A<int> a = new A<int>();

if (a.GetType().IsGenericType && 
    a.GetType().GetGenericTypeDefinition() == typeof(A<>))
{
}

UPDATED:

It looks like this is what you really needed:

public static bool IsSubclassOf(Type childType, Type parentType)
{
    bool isParentGeneric = parentType.IsGenericType;

    return IsSubclassOf(childType, parentType, isParentGeneric);
}

private static bool IsSubclassOf(Type childType, Type parentType, bool isParentGeneric)
{
    if (childType == null)
    {
        return false;
    }

    childType = isParentGeneric && childType.IsGenericType ? childType.GetGenericTypeDefinition() : childType;

    if (childType == parentType)
    {
        return true;
    }

    return IsSubclassOf(childType.BaseType, parentType, isParentGeneric);
}

And can be used like this:

public class A<T>
{
}

public class B : A<int>
{

}

B b = new B();
bool isSubclass = IsSubclassOf(b.GetType(), typeof (A<>)); // returns true;
Andrew Bezzub
?(**new List(of object)**).GetType().GetGenericTypeDefinition is gettype(**List(of )**) ***True***
serhio
Throws exception for non generic types: ?(new ArrayList).GetType().GetGenericTypeDefinition is gettype(List(of ))**Operation is not valid due to the current state of the object.**
serhio
Yes, it is expected behavior.
Andrew Bezzub
fixed, see my own answer.
serhio
Yep, I updated mine too.
Andrew Bezzub
not good. `class B : A(Integer)` this code will not work for B.
serhio
Yes, because B is not a generic type. You can go up through the type hierarchy if you need using type.BaseType() method.
Andrew Bezzub
but I want to detect every instance of A, and every children of A
serhio
I've edited my comment
Andrew Bezzub
not very clear. Need I a special method to detect if myObj is A? If I have C : B : A(T)? or even `Z:Y:X...:C:B:A(T)`?
serhio
Check out updated answer.
Andrew Bezzub
does not work for a "normal" object like string or Form
serhio
How are you using it? I've checked the code - it works.
Andrew Bezzub
ok, very good. Works very well. just fixed some vb.net syntax. Thanks!
serhio
A: 
  Public Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type) As Boolean
    Dim isParentGeneric As Boolean = parentType.IsGenericType

    Return IsSubclassOf(childType, parentType, isParentGeneric)
  End Function

  Private Function IsSubclassOf(ByVal childType As Type, ByVal parentType As Type, ByVal isParentGeneric As Boolean) As Boolean
    If childType Is Nothing Then
      Return False
    End If

    If isParentGeneric AndAlso childType.IsGenericType Then
      childType = childType.GetGenericTypeDefinition()
    End If

    If childType Is parentType Then
      Return True
    End If

    Return IsSubclassOf(childType.BaseType, parentType, isParentGeneric)
  End Function
serhio