I have a BaseClass, a DerivedClass1 and a DerivedClass2 from a third party library. DerivedClass1 and DerivedClass2 both inherit from BaseClass.
There's a ContainerClass, from the same library, with a member variable ActiveItem, which can be of DerivedClass1 or DerivedClass2, so it is declared as BaseClass.
I want to know if ActiveItem is of DerivedClass1, as it can change in runtime without notice.
If I do
Dim isDerivedClass1 as boolean = TypeOf(oject.ActiveItem) Is DerivedClass1
then I get a compile time error, telling me that ActiveItem can never be of DerivedClass1 type.
I have tried several combinations of GetType and TypeOf but it doesn't seem possible to check this. I have also tried to declare an auxiliary DerivedClass1 variable and comparing their types, but haven't got any luck either.
Is there any workaround? I guess I could do it with Reflection, but seems really overkill.
Edit: The following code doesn't compile in vs2005 SP1.
Public Class Base
Public x As Integer
End Class
Public Class Derived1
Inherits Base
Public y As Integer
End Class
Public Class Derived2
Inherits Base
Public z As Integer
End Class
Public Class Unrelated
Public var As Base
End Class
Public Class Form1
Public Sub Test(ByVal obj As Unrelated)
Dim tst As Boolean
tst = TypeOf obj Is Derived1
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim obj As New Unrelated
obj.var = New Derived1
Test(obj)
End Sub
End Class
Edit: It seems that the original problem was a fault in my side. I was checking against the wrong type (those silly third part libraries...) However, I'm still trying to find the error in the code above.
Edit: Again, my fault. I'm checking the Unrelated type against Base.
You code seems to be almost exactly right.
I've done this, which works fine:
Dim isDerivedClass1 As Boolean = TypeOf oject.ActiveItem Is DerivedClass1
Dim isDerivedClass2 As Boolean = TypeOf oject.ActiveItem Is DerivedClass2
Have I missed something?
EDIT: I think you just missed the var
property in your edited code.
Public Sub Test(ByVal obj As Unrelated)
Dim tst As Boolean
tst = TypeOf obj.var Is Derived1
End Sub
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With