Using GetType on a Generic Type

  • Thread starter Thread starter Joe Adams
  • Start date Start date
J

Joe Adams

Hi All,

How can I use GetType(<GenericType>).IsAssignableFrom(<MyType>)

I need to now if the <MyType> is the same type of class as the <GenericType>
without having to add the generic type member members.

i.e. I do not want to use GetType(<GenericType>(Of
String).IsAssignableFrom(<MyType>)

I've tried using
GetType(<GenericType>(Of ,).IsAssignableFrom(<MyType>) but it always returns
false.

Regards
Neal
 
Joe Adams said:
How can I use GetType(<GenericType>).IsAssignableFrom(<MyType>)

I need to now if the <MyType> is the same type of class as the
<GenericType> without having to add the generic type member members.

i.e. I do not want to use GetType(<GenericType>(Of
String).IsAssignableFrom(<MyType>)

I've tried using
GetType(<GenericType>(Of ,).IsAssignableFrom(<MyType>) but it always
returns false.

Assuming you have two types 'A' and 'B', and 'B' inherits from 'A'. In
addition, you have a generic class 'Foo(Of T)'. In this case, 'Foo(Of A)'
is not the supertype of 'Foo(Of B)', althoigh 'A' is the supertype of 'B'!

Thus
'GetType(Object).IsAssignableFrom(Foo(Of ))'
will evaluate to 'True' while
'GetType(Foo(Of A)).IsAssignableFrom(GetType(Foo(Of B))'
evaluates to 'False'.

Assuming you have these classes

\\\
Public Class Foo(Of T)
End Class

Public Class Goo
Inherits Goo(Of Integer)
End Class

Public Class Boo
Inherits Goo
End Class
///

then
'GetType(Foo(Of ).IsAssignableFrom(GetType(Goo))'
will return 'False', although
'GetType(Goo).IsAssignableFrom(GetType(Boo))'
returns 'True'.
 
Thank's for that, So it appears that IsAssignable function only works with
specified generics types not generic definition types.

The following function now does what I need.
Called like so

IsAssignableFromGenericType(<SomeTypeToCheck>,
GetType(BusinessListBase(Of )))
Private Function IsAssignableFromGenericType(ByVal typeToCheck As
System.Type, ByVal genericTypeToCompare As System.Type) As Boolean

Do

If typeToCheck.IsGenericType Then

Dim genTypeDef As System.Type = typeToCheck.GetGenericTypeDefinition

If genTypeDef.Equals(genericTypeToCompare) Then

Return True

End If

End If

typeToCheck = typeToCheck.BaseType

Loop While typeToCheck.BaseType IsNot Nothing

End Function


Regards
 
Joe Adams said:
Thank's for that, So it appears that IsAssignable function only works with
specified generics types not generic definition types.

Yes, that's true. Otherwise there is no subtyping relation between the
types.
 
Back
Top