0

How do I find the class type that inherited the class running the shared function? Is this possible?

Public Class Class1
    Inherits ClassFunctions
End Class
Public Class Class2
    Inherits ClassFunctions
End Class
Public Class ClassFunctions
    Public Shared Function GetParentName() As String
        Dim name As String = ""
        '?
        Return name
    End Function
End Class
Public Module Example
    Public Name1 As String = Class1.GetParentName() 'Class1
    Public Name2 As String = Class2.GetParentName() 'Class2
End Module
bchiemara
  • 3
  • 3
  • You [cannot](https://stackoverflow.com/q/248263/11683) have that with shared functions. With instance functions, it's `Me.GetType().Name`. – GSerg Aug 03 '20 at 17:24
  • This sounds like an XY problem. Maybe explain what you're trying to achieve, rather than how you're trying to achieve it. What's the endgame here? Are you just trying to find out what the base class is for any particular type? If so then that's easy and doesn't require you to write your own `Shared` method, but you need to actually explain that. – jmcilhinney Aug 04 '20 at 00:52

1 Answers1

1

As the name Shared says, the Function is shared, but not inherited as would an instance method. Therefore, its parent type is always the original parent type (even when called from a derived class). This function always returns ClassFunctions even when called from Class1 or Class2:

'Failing attempt to return "inheriting" class name
Public Shared Function GetParentName() As String
    Dim stack As New StackTrace
    Dim className As String = stack.GetFrame(0).GetMethod.ReflectedType.Name
    Return className
End Function

With an instance method you can write

'This works
Public Function GetParentName() As String
    Return Me.GetType().Name
End Function

But you must call it from an object, and it returns the type name of this object.


A working solution with shared functions is to use Shadowing in Visual Basic, i.e., to hide the parent implementation and provide a new one. The disadvantage is that this mechanism does not automatically produce the desired class names. You must implement it explicitly in each class:

Public Class ClassFunctions
    Public Shared Function GetParentName() As String
        Return NameOf(ClassFunctions)
    End Function
End Class

Public Class Class1
    Inherits ClassFunctions

    Public Shared Shadows Function GetParentName() As String
        Return NameOf(Class1)
    End Function
End Class

Public Class Class2
    Inherits ClassFunctions

    Public Shared Shadows Function GetParentName() As String
        Return NameOf(Class2)
    End Function
End Class

Instead of providing the name as string literal, I used the NameOf operator. The advantage over the former is that the correctness of the name is tested by the VB compiler.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188