Check if a class type can be created with an activator without an instance.

Currently, when I have a class type and you need to know if the class can be created. I will call Activator.CreateInstance(type); and throw out the result.

This seems very inefficient and problematic.

Is there an alternative way to confirm that an instance type can be created for the current application?

I need to run this test as part of launching an application. To ensure that any incorrect configuration is detected before. If I leave it until an instance of the class is needed, an error can occur when no one is fixed.

Here is what I am doing 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); } 
+6
source share
2 answers

Depending on what can be found here , you can check whether the type contains a constructor without parameters (which classes will be by default if not provided), and whether the type will be non-abstract:

 if(classType.GetConstructor(Type.EmptyTypes) != null && !classType.IsAbstract) { //this type is constructable with default constructor } else { //no default constructor } 
+7
source

Using System.Runtime.Serialization.FormatterServices.GetUninitializedObject (type) will instantiate the object, but will not call the constructor. It displays a null instance of the class. The class must be available or an exception is thrown. If your class has a detailed launch code, this can improve efficiency.

+2
source

Source: https://habr.com/ru/post/956799/


All Articles