Tuesday, February 20, 2007

How to check the executing Type from the base class

Occasionally when designing base classes we need to know the type of the inheriting class executing the method (i.e. like when you're loading types from other assemblies dynamically or when it's not possible to change the inherited classes). You can either use the TypeOf operator in VB or use the GetType method that is available in the CLR to accomplish this.

Module Module1
    Sub Main()
        Dim a As New A
        Console.WriteLine(a.Method1())
 
        Dim b As New B
        Console.WriteLine(b.Method1())
 
        Dim c As New C
        Console.WriteLine(c.Method1())
 
        Console.ReadLine()
    End Sub
End Module
 
Public MustInherit Class Base
 
    Function Method1() As String

        If TypeOf Me Is A Then
            Return "Hello from A"

        ElseIf TypeOf Me Is B Then
            Return "Hello from B"

        Else
            Return String.Format("Hello from {0}", Me.GetType.ToString)
        End If

    End Function
End Class

Public Class A
    Inherits Base

End Class

Public Class B
    Inherits Base

End Class

Public Class C
    Inherits Base

End Class

2 comments:

Greg said...

This is a big no no .. never do this. Parents should never be aware of their children. you can easily handle this case by using polymorphism instead ... the derived class should be providing a method the parent calls.

Beth Massi said...

Never is a pretty harsh word ;-). I agree that most of the time you should avoid this and ask yourself why it is necessary -- i.e. would refactoring my classes fix this? But this can come in quite handy if you're loading types dynamically or if you cannot change the child classes.