Dynamically instance a class

A

APA

I have a setting in my database where the user specifies a tax configuration (e.g. "UK/EU") and I have several tax classes that handle these
different configurations. So what is the best way to instance the proper class based on what is in this configuration parameter. I could use a
simple switch statement but it seems like there should be a better way.
 
M

Mattias Sjögren

I have a setting in my database where the user specifies a tax configuration (e.g. "UK/EU") and I have several tax classes that handle these
different configurations. So what is the best way to instance the proper class based on what is in this configuration parameter. I could use a
simple switch statement but it seems like there should be a better way.

You could store the corresponding type name in a table (either in the
database or in your code, e.g. a hashtable) and use that create the
right type of object. The System.Type.GetType and
System.Activator.CreateInstance methods may be helpful.


Mattias
 
C

Carl Daniel [VC++ MVP]

APA said:
I have a setting in my database where the user specifies a tax
configuration (e.g. "UK/EU") and I have several tax classes that handle
these different configurations. So what is the best way to instance the
proper class based on what is in this configuration parameter. I could use
a simple switch statement but it seems like there should be a better way.

Store the full name of the class in your database (perhaps in a table of
it's own with a small surrogate key in your other tables). Then use
Type.GetType(typeName) to get the type, and
Activator.CreateInstance(yourType) to create an instance of the class. If
you need to pass in constructor parameters, you can use
Type.GetConstructor() to get a ConstructorInfo object, then use
ConstructorInfo.Invoke() to instantiate the type, passing in your
constructor parameters.

-cd
 
P

Paul

If you use these techniques and also ( as they are doing the same job )
ensure your tax classes implement a known interface.

For example

public interface IProcessTax
{
double processTax(double value);
}

this will minimise the amount of reflection requried.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top