2

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.