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.