Created
June 5, 2018 18:24
-
-
Save ScottHutchinson/8b7c29cfd568cc4219c41ba0dde4ff12 to your computer and use it in GitHub Desktop.
VB .NET TypeOf Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Module Module1 | |
Class ClsTrack | |
End Class | |
Class ClsVehicularTrack : Inherits ClsTrack | |
End Class | |
Class ClsSpecialTrack : Inherits ClsTrack | |
End Class | |
Sub Main() | |
Dim myTrack1 As ClsTrack = New ClsVehicularTrack() | |
Dim myTrack2 As ClsTrack = New ClsSpecialTrack() | |
Dim myVehicularTrack1 As ClsVehicularTrack | |
Dim myVehicularTrack2 As ClsVehicularTrack | |
Dim typeOfmyTrack1 As Type = myTrack1.GetType() | |
Dim typeOfmyTrack2 As Type = myTrack2.GetType() | |
Console.WriteLine("myTrack1 is a {0}", typeOfmyTrack1.Name) ' --> "myTrack1 is a ClsVehicularTrack" | |
Console.WriteLine("myTrack2 is a {0}", typeOfmyTrack2.Name) ' --> "myTrack2 is a ClsSpecialTrack" | |
If myTrack1.GetType().Name = "ClsVehicularTrack" Then | |
myVehicularTrack1 = myTrack1 | |
Console.WriteLine("myVehicularTrack1 is a {0}", myVehicularTrack1.GetType().Name) ' --> "myTrack1 is a ClsVehicularTrack" | |
'Else do something else... | |
End If | |
If myTrack2.GetType().Name = "ClsVehicularTrack" Then ' <-- This condition prevents the InvalidCastException | |
myVehicularTrack2 = myTrack2 ' --> InvalidCastException (cannot assign a ClsSpecialTrack to a ClsVehicularTrack) | |
Console.WriteLine("myVehicularTrack2 is a {0}", myVehicularTrack2.GetType().Name) ' --> not reached | |
'Else do something else... | |
End If | |
If TypeOf myTrack1 Is ClsVehicularTrack Then | |
myVehicularTrack1 = myTrack1 | |
Console.WriteLine("TypeOf myVehicularTrack1 is a {0}", myVehicularTrack1.GetType().Name) | |
'Else do something else... | |
End If | |
If TypeOf myTrack2 Is ClsVehicularTrack Then ' <-- This condition prevents the InvalidCastException | |
myVehicularTrack2 = myTrack2 ' --> InvalidCastException (cannot assign a ClsSpecialTrack to a ClsVehicularTrack) | |
Console.WriteLine("myVehicularTrack2 is a {0}", myVehicularTrack2.GetType().Name) ' --> not reached | |
'Else do something else... | |
End If | |
Console.WriteLine("Press any key to exit...") | |
Console.ReadKey() | |
End Sub | |
End Module |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment