Question Checking Objects' Type by string

qxface

New member
Joined
Apr 15, 2011
Messages
1
Programming Experience
5-10
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:
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:
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!
 
With Type.GetType method you need to qualify the namespace to the type if in assembly (for example "WindowsApplication1.properNoun") , or use the full AssemblyQualifiedName if not.
When you have the Type instance you can use Type.IsAssignableFrom method to check for type relation.
An example related to your code:
VB.NET:
Dim myType = Type.GetType(pn.GetType.AssemblyQualifiedName)
Dim assignable = GetType(noun).IsAssignableFrom(myType) ' True
 
Back
Top