Object-oriented DirectCasting
Trudging through object-oriented forest leads to some interesting results. The beauty of a strongly-typed language must also be it’s biggest downfall. In VB.NET in order to implement a polymorphic design pattern on a sensor class I had to learn the magic of DirectCasting an object. See the example below:
Public Class Form1
Dim WithEvents oBaseClass As BaseClass
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
oBaseClass = New ExtendedClass
oBaseClass.Test() 'This doesn't work because the object was type casted.
End Sub
Private Sub TestEventHdlr() Handles oBaseClass.TestEvent
MsgBox("Event Fired")
End Sub
End Class
Public Class BaseClass
Public Event TestEvent()
End Class
Public Class ExtendedClass
Inherits BaseClass
Public Sub Test()
MsgBox("Test")
End Sub
End Class
Surprisingly this does not work!
The issue lies in direct-casting. In order to use extended functions inside an object one must direct cast it, like this:
Public Class Form1
Dim WithEvents oBaseClass As BaseClass 'Early bound'