Return the object associated with the name
-
22-04-2021 - |
Question
I'm connecting my program to some external code. I'm setting it up so that the external code can instance objects and I've come across a problem. I've created this function here:
Public Function InstanceOf(ByVal typename As String) As Object
Dim theType As Type = Type.GetType(typename)
If theType IsNot Nothing Then
Return Activator.CreateInstance(theType)
End If
Return Nothing
End Function
I'm trying to create a System.Diagnostics.Process
object. For what ever reason though, it always return Nothing
instead of the object. Does anybody know what I'm doing wrong?
I'm doing this in VB.net so all .net responses are accepted :)
Solution
Read carefully through the documentation of Type.GetType()
, specifically, this part:
If typeName includes the namespace but not the assembly name, this method searches only the calling object's assembly and Mscorlib.dll, in that order. If typeName is fully qualified with the partial or complete assembly name, this method searches in the specified assembly. If the assembly has a strong name, a complete assembly name is required.
Since System.Diagnostics.Process
is in System.dll (not Mscorlib.dll), you need to use the fully qualified name. Assuming you're using .Net 4.0, that would be:
System.Diagnostics.Process, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
If you don't want to work with fully qualified names, you can go through all loaded assemblies and try to get the type using Assembly.GetType()
.
OTHER TIPS
you could use something like this for creating your Objects.
I defined a local class and also used your process example.
Public Class Entry
Public Shared Sub Main()
Dim theName As String
Dim t As Type = GetType(AppleTree)
theName = t.FullName
Setup.InstanceOf(theName)
t = GetType(Process)
theName = t.FullName & ", " & GetType(Process).Assembly.FullName
Setup.InstanceOf(theName)
End Sub
End Class
Public Class Setup
Shared function InstanceOf(typename As String) as object
Debug.Print(typename)
Dim theType As Type = Type.GetType(typename)
If theType IsNot Nothing Then
Dim o As Object = Activator.CreateInstance(theType)
'
Debug.Print(o.GetType.ToString)
return o
End If
return nothing
End function
End Class
Public Class AppleTree
Public Sub New()
Debug.Print("Apple Tree Created")
End Sub
End Class