Test if a class type can be instantiated with Activator without instantiating it
Asked Answered
M

2

10

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);
        }
Manciple answered 26/10, 2013 at 20:25 Comment(0)
A
11

Based on what can be found here, you could test whether the type contains a parameterless constructor (which classes will by default when not provided), and whether the type is not abstract:

if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract)
{
     //this type is constructable with default constructor
}
else
{
   //no default constructor
}
Ague answered 26/10, 2013 at 20:32 Comment(2)
I think in addition of checking for having parameter constructor and not being abstract , we should check , if the type is not static.Tours
@Parsa, static class has no instance constructor so GetConstructor will be null. It would be good to check if class is generic.Ferrochromium
A
3

Using System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type) will instantiate the object but will not call upon the constructor. It renders a zeroed out instance of the class. The class must be accessible or an exception is thrown. If your class has verbose startup code then this may improve on efficiency.

Allinclusive answered 26/10, 2013 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.