Thursday, September 16, 2010

Comparing instance is type of a class

There are various kinds of ways to check whether a object is instance of given class or not. The following are some of the ways that has been identified to be find this condition

Public Interface MyMarkerInterface
 
End Interface
 
Public Class myTestCls
    Implements MyMarkerInterface
         Private _m As Integer
    Public ReadOnly Property Age() As Integer
        Get
            Return _m
        End Get
    End Property
 
End Class

The above is the class that implements some interface........ So in some case I want to check whether the instance of above class is instance of Interface.


    Private Function isMarkerkedObj1(ByVal o1 As myTestClsAs Boolean
        If TypeOf o1 Is MyMarkerInterface Then
            Return True
        Else
            Return False
        End If
    End Function
 
    Private Function isMarkerkedObj2(ByVal o1 As myTestClsAs Boolean
        If o1.GetType.IsSubclassOf(GetType(MyMarkerInterface)) Then
            Return True
        Else
            Return False
        End If
    End Function
 
    Private Function isMarkerkedObj3(ByVal o1 As myTestClsAs Boolean
        If GetType(MyMarkerInterface).IsAssignableFrom(o1.GetType) Then
            Return True
        Else
            Return False
        End If
    End Function
Now all the above methods are using different methods to compare the type of object to check is this type of particular kind .

e.g. Dim obj1 as new myTestCls
-------------
------------- 
-------------
isMarkerkedObj1(obj1)
isMarkerkedObj2(obj1)
isMarkerkedObj3(obj1)

all the above calls will return true.

Note: The requirement discussed might be confusing but is very useful in many scenarios a the interface used is a marker interface which consists of nothing in the body. So in certain cases we may require to mark some objects for certain behavior then we use this interface.

No comments: