Currently when I have a class type and need to know if the class can be created. I will call Activator.CreateInstance(type);
and throw away the result.
This seems very inefficient and problematic.
Is there an alternative way to confirm that a class type can be instantiated for the current application?
I need to do this test as part of the application startup. To ensure that any misconfiguration is caught early. If I leave it until an instance of the class is required, then the error could occur when no one is around to fix it.
Here is what I do now.
string className = string.Format("Package.{0}.{1}", pArg1, pArg2);
Type classType = Type.GetType(className);
if (classType == null)
{
throw new Exception(string.Format("Class not found: {0}", className));
}
try
{
// test creating an instance of the class.
Activator.CreateInstance(classType);
}
catch (Exception e)
{
logger.error("Could not create {0} class.", classType);
}