How to create an object by class name using Reflection

1. When the class is defined in the same assembly, where your code is executed:

1
2
3
4
Dim _assemblyName As String = "MyAssembly"
Dim _typeName As String = "MyNamespace.ExampleControl"
Dim _type As Type = Assembly.Load(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)
Dim _assemblyName As String = "MyAssembly"
Dim _typeName As String = "MyNamespace.ExampleControl"
Dim _type As Type = Assembly.Load(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)

2. If the class remains in a different assembly, then you will need to provide a full qualified assembly name, like
“ExampleAssembly, Version=1.0.0.0, Culture=en, PublicKeyToken=a5d015c7d5a0b012” (see more about the full qualified assembly names here: http://msdn.microsoft.com/en-us/library/system.reflection.assemblyname.aspx)

For instance, if you need to create an instance of System.Windows.Controls.DatePicker control:

1
2
3
4
Dim _assemblyName As String = "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Dim _typeName As String = "System.Windows.Controls.DatePicker"
Dim _type As Type = Assembly.Load(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)
Dim _assemblyName As String = "PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Dim _typeName As String = "System.Windows.Controls.DatePicker"
Dim _type As Type = Assembly.Load(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)

3. If, for any reason, you need to use a short assembly name, like “PresentationFramework” rather than a full qualified name given in previous example, then you can use the deprecated function LoadLoadWithPartialName, like in the following example:

1
2
3
4
Dim _assemblyName As String = "PresentationFramework"
Dim _typeName As String = "System.Windows.Controls.DatePicker"
Dim _type As Type = Assembly.LoadLoadWithPartialName(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)
Dim _assemblyName As String = "PresentationFramework"
Dim _typeName As String = "System.Windows.Controls.DatePicker"
Dim _type As Type = Assembly.LoadLoadWithPartialName(_assemblyName).GetType(_typeName, True)
_control = Activator.CreateInstance(_type)

For more information about the reflection, please refer to MSDN: http://msdn.microsoft.com/en-us/library/f7ykdhsy(v=vs.110).aspx.

Leave a comment

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