Dynamically instance a class

  • Thread starter Thread starter APA
  • Start date Start date
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.
 
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
 
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
 
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.
 
Back
Top