Reputation: 5555
I want to instance a class depending on a combobox selection. Let say I have the following classes and interface:
Public Interface Sports
Sub description()
End Interface
Public Class Football : Implements Sports
Public Sub description() Implements Sports.description
MsgBox("Football")
End Sub
End Class
Public Class Hockey : Implements Sports
Public Sub description() Implements Sports.description
MsgBox("Hockey")
End Sub
End Class
One solution for my client looks like:
Dim test As Sports
if combobox.selectedtext = "Football" then
test = New Football
else
test = New Hockey
end if
test.description()
With many subclasses this can be quite long, so I was thinking about a way to instance the chosen class depending on the selected text. I know this looks stupid, but something like:
Dim text As String = ComboBox1.SelectedText
test = New "test"
Is it possible to instance a class depending on an assigned string?
Upvotes: 2
Views: 89
Reputation: 15821
You can dynamically instantiate a type based on its unqualified name by searching for the type:
// Find the type by unqualified name
var locatedType = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault( type => type.Name == "Football" );
// Create an instance of the type if we found one
Sports sportsInstance = null;
if( locatedType != null ){
sportsInstance = (Sports)Activator.CreateInstance( locatedType );
}
This will search the current assembly for a type matching the name "Football" and instantiate it if it was found.
Upvotes: 1
Reputation: 12325
You can use the Activator.CreateIntance method to create a new instance.
This method requires a Type
be passed in, so if you only have the string, you'll need to combine the method with Type.GetType:
Activator.CreateInstance(Type.GetType(ComboBox1.SelectedText))
You'll then need to cast the returned Object
to Sports
if you want to assign it to your variable.
Note: The ComboBox will need to list the full type name (name and namespace) otherwise Type.GetType
will not work.
Upvotes: 1