Edmund Ireland
Edmund Ireland

Reputation: 1

VB.net: Creating one of several derived class objects in response to User

This seems like it should be a really easy question to answer, but I can't seem to find any obvious way to do it.

I have a base class for an object, and it has several derived classes, here ClassA and Class B. I want to take input from the user and create an object of a type determined by their response.

But I can't just put a Dim statement inside a Select Case because the block scope will kill the object immediately.

What I want is something like

Select Case Input Case 1 Dim OutputObject as New ClassA() Case 2 Dim OutputObject as New ClassB() End Select

I keep feeling there is some obvious way to do this, after all it seems fairly important to the whole idea of polymorphism, but I can't seem to think of it.

Upvotes: 0

Views: 83

Answers (1)

the_lotus
the_lotus

Reputation: 12748

This is called a Factory Method. It would look more like this

Dim OutputObject as BaseClass

Select Case Input
Case 1
    OutputObject = New ClassA()
Case 2
    OutputObject = New ClassB()
End Select

Where you would return the base class.

Upvotes: 1

Related Questions