Object Type Equals Comparison [vb.net]

NeuralJack

Centurion
Joined
Jul 28, 2005
Messages
138
Lets say I want to find out the Type of an Object - I often use tags. In order to do this do I really have to instantiate another new object to compare the tag object to? for instance

Visual Basic:
'Lets say obj is a Tag object imported into the function
Private Function IsObjMyClass(obj as Object) as boolean
        Dim MC1 As New MyClass1  'Do I really need to create an object here?
   
        If Object.ReferenceEquals(obj.GetType(), MC1.GetType()) Then
           Return True
        Else
           Return False
        End If
End Function
 
TypeOf operator

Use the TypeOf operator:

Visual Basic:
'Lets say obj is a Tag object imported into the function
Private Function IsObjMyClass(obj as Object) as boolean
        If TypeOf obj Is MyClass1 Then
           Return True
        Else
           Return False
        End If
End Function

Or simpler:

Visual Basic:
'Lets say obj is a Tag object imported into the function
Private Function IsObjMyClass(obj as Object) as boolean
        Return (TypeOf obj Is MyClass1)
End Function

Good luck :cool:
 
There is one difference between the two methods:
Visual Basic:
If Object.ReferenceEquals(obj.GetType(), MC1.GetType()) Then
    'obj is an instance of MyClass1
End If
If TypeOf obj Is MyClass1 Then
    'obj is instance of MyClass1 or a derived class
End If
 
Back
Top