Getting a Type by its name

The Type.GetType() makes it real easy to get a handle on a Type object. However there is a gotcha here because it might not always work as expected. Try the following code:
Module Module1
    Sub Main()
        Dim type1 As Type
        type1 = GetType(MyType)
        Dim type2 As Type
        type2 = Type.GetType(type1.FullName)
PublicClass MyType
If you run this code the type name will be printed twice, no big surprises here. Now move the MyType to a ClassLibrary project and set a reference to it. This time the type2 variable is nothing event though the type exists, after all type1 is still a valid reference.
To get this working you need to use the following:
Dim typeName AsString
typeName = type1.AssemblyQualifiedName
typeName = typeName.Substring(0, typeName.IndexOf(“, Version=”))
type2 = Type.GetType(typeName)
So why not just use the complete AssemblyQualifiedName? Well it contains a version as well as public key token name and of the assembly is signed it looks for an exact version match, not a problem in a this small sample but in a remoting scenario that might cause a new set of problems.
Maurice de Beijer

Leave a Reply

Your email address will not be published. Required fields are marked *