Getting a Type by full name and creating an instance of it using Activator
Yesterday was my first work day in my new company. Today I needed to go through a part of components developed by the company. I created a WinForms application with several forms. I used each form to test different controls using different configuration. The application has one main form with buttons - one button per form. Each button’s Text property is set to the name of the form it opens. I decided to use only one event handler for button click event and to implement as less code as possible. And I came into the code snippet below. It uses Assembly class in order to retrieve target type by its full name (line 6-7). It also checks if retrieved type is assignable from Form (line 13). If all is OK an instance of retrieved type is created using Activator class and it is used to show the form as an dialog (line 18-20).
C# implementation.
[sourcecode language="csharp"]
private void button_Click(object sender, EventArgs e)
{
string fullTypeName = string.Format(”{0}.{1}”, _namespace, (sender as Button).Text);
Type type = Assembly.GetExecutingAssembly()
.GetType(fullTypeName);
if (type == null)
{
return;
}
if (!typeof(Form).IsAssignableFrom(type))
{
return;
}
Form form = Activator.CreateInstance(type) as Form;
form.ShowDialog();
form.Dispose();
}
[/sourcecode]
VB.Net implementation.
[sourcecode language="vb"]
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click, Button2.Click
Dim typeFullName As String = String.Format(”{0}.{1}”, _namespace, CType(sender, Button).Text)
Dim assembly As Assembly = assembly.GetExecutingAssembly()
Dim type As Type = assembly.GetType(typeFullName)
If type Is Nothing Then
Return
End If
If GetType(Form).IsAssignableFrom(type) = False Then
Return
End If
Dim form As Form = CType(Activator.CreateInstance(type), Form)
form.ShowDialog()
form.Dispose()
End Sub
[/sourcecode]
Leave a Reply