Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Testing object type

Status
Not open for further replies.

Monkey36

MIS
May 23, 2005
60
GB
I'm not quite sure how to explain why I want to do this without going into a long-winded explanation, so I'll just skip that bit.

I'm wondering if anyone can help me out with some code to determine object type - essentially, I've got an object that may be an instance of one of two types, and I'd like to test which it is, but I can't for the life of me work out how!

Code:
Dim obj As Object = New Class1

If (obj Is Class1) Then
 MsgBox("Object is of type Class1")
ElseIf (obj Is Class2) Then
 MsgBox("Object is of type Class2")
Else
 MsgBox("Don't know!")
End If

Well, you get the idea, this is what I'd like to do, but this code doesn't work ("'Class1' is a type and cannot be used as an expression"), but I can't find out how I should do it!

Do be honest, I'm struggling a bit find search terms to put into Google to help me out.

If anyone could point me in the right direction it would be much appreciated!

Cheers,
Dan.
 
You could use TypeOf as follows:

Dim obj As New Class1
If TypeOf obj Is Class1 Then
MessageBox.Show("Class1")
ElseIf TypeOf obj Is Form1 Then
MessageBox.Show("Form1")
Else
MessageBox.Show("Unknown")
End If

Hope this helps.
 
I misread your original code sample - this also works:

Dim obj As Object = New Class1
If TypeOf obj Is Class1 Then
MessageBox.Show("Class1")
ElseIf TypeOf obj Is Form1 Then
MessageBox.Show("Form1")
Else
MessageBox.Show("Unknown")
End If

Hope this helps.
 
Not sure this adds much to the discussion, but you can always use obj.Name to display it.

Have a great day!

j2consulting@yahoo.com
 
earthandfire - thank you! I was sure I'd seen it done before, but I couldn't for the life of me find it!

Thanks a lot,
Dan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top