Checking an object's parent types by string
Hello,
I'm trying to figure out how find an object's type when it is a subclass of another object and I only know the string value of the object's type's name.
Sorry if this is a convoluted questions.
I created the follwing classes:
HTML Code:
Public Class word
End Class
Public Class noun
Inherits word
End Class
Public Class properNoun
Inherits noun
End Class
Then, in my code I create a new properNoun and check to see if it is a properNoun, noun or word:
HTML Code:
Private Sub checkTypes()
Dim pn As New properNoun
MsgBox("Is a properNoun: :" & TypeOf pn Is properNoun) 'TRUE
MsgBox("Is a noun: :" & TypeOf pn Is noun) 'TRUE
MsgBox("Is a word: :" & TypeOf pn Is word) 'TRUE
MsgBox("typeOf properNoun: :" & (pn.GetType.Name.ToString = "properNoun")) 'TRUE
MsgBox("typeOf noun: :" & (pn.GetType.Name.ToString = "noun")) 'FALSE
MsgBox("typeOf word: :" & (pn.GetType.Name.ToString = "word")) 'FALSE
Dim myType As Type = Type.GetType("properNoun")
MsgBox(TypeOf pn Is myType) 'ERROR: "Type myType is not defined"
MsgBox(TypeOf pn Is Type.GetType("properNoun")) 'ERROR "Type 'Type.getType' is not defined
End Sub
Using 'TypeOf', I correctly see that pn is a properNoun, a noun and a word.
The problem is, using 'GetType' to check pn against a string value, I can only see that pn is a properNoun, not that its parent classes are noun and word.
Is there a way to check pn against the string value "noun" or "word" and get back a positive result, indicating that pn is indeed a noun and a word as well as a properNoun?
Thanks for any help!
Re: Checking an object's parent types by string
I am curious as to why you want to do this, but:
vb.net Code:
Public Function CheckInheritance(ByVal c As Type, _
ByVal fullName As String) As Boolean
Dim current = c.BaseType
Do Until current Is Nothing
If current.FullName.Equals(fullName) Then
Return True
End If
current = current.BaseType
Loop
Return False
End Function
Example usage:
vb.net Code:
'//this call expects the fully qualified name
Dim t = Type.GetType("WindowsApplication1.ProperNoun")
Console.WriteLine("Inherits Word? {0}", _
Me.CheckInheritance(t, "WindowsApplication1.Word"))
Console.WriteLine("Inherits Noun? {0}", _
Me.CheckInheritance(t, "WindowsApplication1.Noun"))
Re: Checking an object's parent types by string
That works perfectly. Thank you!
If you're wondering why I want to do this, it's because the classes that I'll be testing against won't be known until they are read in from a text file at run time. So I'll have to test against an array of strings containing names of classes.
Thank you again for your help!