Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check the final type of a variable?

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.

like image 739
raven Avatar asked Feb 26 '23 07:02

raven


1 Answers

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
like image 148
Enigmativity Avatar answered Feb 28 '23 19:02

Enigmativity