Home All Groups Group Topic Archive Search About

Can reflection tell the base class of an object?

Author
3 Nov 2006 4:22 PM
stktung
Hey guys,

Are there functions in reflection that gives information about the base
classes of an object?

Thanks in advance
-Steve

Author
3 Nov 2006 5:05 PM
Mike McIntyre
Check out the Type class's GetBaseType method.

http://msdn2.microsoft.com/en-us/library/system.type_members.aspx

--
Mike

Mike McIntyre [MVP]
http://www.getdotnetcode.com


<stkt***@yahoo.com> wrote in message
Show quoteHide quote
news:1162570961.222895.124290@m73g2000cwd.googlegroups.com...
> Hey guys,
>
> Are there functions in reflection that gives information about the base
> classes of an object?
>
> Thanks in advance
> -Steve
>
Author
3 Nov 2006 7:10 PM
Mythran
<stkt***@yahoo.com> wrote in message
news:1162570961.222895.124290@m73g2000cwd.googlegroups.com...
> Hey guys,
>
> Are there functions in reflection that gives information about the base
> classes of an object?
>
> Thanks in advance
> -Steve
>

Here's an example:

Private Sub ShowInheritanceTree(ByVal Instance As Object)
    Dim t As Type = Instance.GetType()
    Dim n As Integer = 0
    Dim tmp As Type = t
    Dim names As ArrayList = New ArrayList()

    While Not tmp Is GetType(Object)
        If tmp Is Nothing
            tmp = t.BaseType
        Else
            tmp = tmp.BaseType
        End If

        names.Add(tmp.Name)
        n += 1
    End While

    Dim line As String
    Dim spaces As String
    For i As Integer = n - 1 To 0 Step -1
        line = String.Empty
        If i < n - 1
            spaces = StrDup(((n - 1) - i) * 4, " ")
            line = spaces & "|" & vbNewLine & spaces & "--- "
        End If

        line &= CStr(names(i))
        Console.WriteLine(line)
    Next i
End Sub

This method goes up the inheritance tree looking for the base types of each
class the current class inherits from then reverses the search to display
each class from top-to-bottom.

HTH,
Mythran