Re: How to dynamically instantiate a class

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance

From: SP (egatsecneserp(reverse)_at_hotmail.com)
Date: 07/25/04


Date: Sat, 24 Jul 2004 22:44:40 -0400


> What I really want to do is something like this:
>
> Main {
> string classToInstantiate;
> if (something) classToInstantiate = "class1";
> if (something) classToInstantiate = "class2";
> fn(classToInstantiate);
> }
>
> fn (string theClass) {
> // logic to instantiate the class that is the value of theClass
> }

You should really use a separate Factory object but for a quick example it
would be

MyAbstractClass a (or IMyInterface a)
if(something) a = new Class1();
if(somethingElse) a = new Class2();

Of course Class1 and Class2 both need to implement IMyInterface or inherit
MyAbstractClass

SP