Best way to compare object types?

ajeeshco

Well-known member
Joined
Sep 19, 2006
Messages
257
Location
Cochin, India
Programming Experience
3-5
Hi,
I have to compare objects and I think I have better options like

VB.NET:
TypeOf obj Is ClassLibrary1.Class1

and

VB.NET:
obj.GetType Is GetType(ClassLibrary1.Class1)

Now I'm confused which one to use, and would like to know which one is better? if is better then why?

Thanks in Advance.
 
TypeOf operator tells if type of object is same or compatible (inherited or implements interface), GetType operator tells if type is exactly the same.
VB.NET:
Dim bTrue As Boolean = TypeOf New TextBox Is TextBoxBase
Dim bFalse As Boolean = (New TextBox).GetType Is GetType(TextBoxBase)
 
TypeOf operator tells if type of object is same or compatible (inherited or implements interface), GetType operator tells if type is exactly the same.
VB.NET:
Dim bTrue As Boolean = TypeOf New TextBox Is TextBoxBase
Dim bFalse As Boolean = (New TextBox).GetType Is GetType(TextBoxBase)
Good point, although that's rarely a distinction you need to make. The GetType method of an object is normally used as a starting point for reflection. It returns a Type object that you can use to get information about members via reflection.
 
True, I always use TypeOf comparison myself, it has a better sound to it when reading the code also IMO, but for the special cases there is a difference and I think this is what ajeeshco wanted to know. When the type to compare is identical the result of these methods is the same.
 
Back
Top