How can I get a sub-class name in Visual Basic

Viewed 608

I have a Visual Basic method called LogException which writes information into my Exceptions database in the event of a TRY..CATCH failure. That method has the following parameters:

  1. methodLocation;
  2. methodName;
  3. exception;

When I invoke the method, I would use the following code:

_ex.LogException(
    Me.GetType.Name.ToString,
    MB.GetCurrentMethod.Name.ToString,
    ex.Message.ToString)

Therefore, if I was invoking this code in a method called "Insert_Test" within a class called "Test", I would expect the first parameter to receive "Test", the second to receive "Insert_Test" and the third to receive the exact details from the exception that was thrown.

This all works fine as long as the "Test" class is the base class. If the "Test" class is a sub-class (for example called "BigTest"), the first two parameters would still be passed as "Test" and "Insert_Test". What I need to know is how to get the exact class tree, so that the first parameter in this scenario would come through as "BigTest.Test".

Ideally I'd like to be able to do this without having to hard-code any values into my code, so that the code can be re-used "as-is".

2 Answers

You could use a function like this:

Public Function GetFullType(ByVal type As Type) As String
    Dim fullType As String = ""

    While type IsNot GetType(Object)
        If fullType = "" Then
            fullType &= type.Name
        Else
            fullType = type.Name & "." & fullType
        End If

        type = type.BaseType
    End While

    Return fullType
End Function

And call it like this:

GetFullType(Me.GetType)

EDIT: It appears as though the OP is actually using nested classes, not inherited classes. In such case I found this answer which should be able to tweak into the code provided.

Code for nested classes:

Shared Function GetFullType(ByVal type As Type) As String
    Dim fullType As String = ""

    While type IsNot Nothing
        If fullType = "" Then
            fullType &= type.Name
        Else
            fullType = type.Name & "." & fullType
        End If

        type = type.DeclaringType
    End While

    Return fullType
End Function
Related