0

I would like to be able to verify that a class exists within the current assembly before attempting to create it using Activator.CreateInstance.

Currently I build a fully qualified class name based on some meta-data retrieved from a 3rd party application I am extending. This class name is then created using Activator.CreateInstance and cast to a common base class.

I'm looking for something along the lines of:

string className = "MyNamespace." + "some_arbitary_class_name";
if (Assembly.ClassExists(className))
{
     // Create the class.
}

Currently I have this:

 string class_name = "MyNamespace.BaseClassImpl_" + meta_data;
 MyBaseClass baseClass = null;
 try
 {
     baseClass = (BaseClass)Activator.CreateInstance(null, class_name);
 }
 catch (Exception e) { }
 // If base class in null, failed.

I know that I need to use System.Reflection to inspect the current assembly but I'm at a loss of the exact methods I need to use.

So my question is twofold:

  1. Could someone please direct me to the .NET api I need to use to accomplish this?
  2. Is it good practice to verify that a class exists before creating it? Or should I just let the try-catch block handle it?

2 Answers 2

3

You could do an Assembly.GetType("assembly") and see if that returns null, there is also another overload that allows you to specify a parameter of whether to throw if if the type doesnt exist.

If you can I'd say its probably best to avoid the exception, it will probably make your code harder to read at the very least.

1
  • Thanks Daniel, this is what I was after. Accepting this as my answer but I'll post what I ended up doing so any future viewers can see the end result. Sep 6, 2013 at 6:25
0

Daniel Powells answer was exactly what I needed to get this done.

In the end, this a rough translation of the code I used to achieve what I needed to do:

class MyBaseClass
{   }

class MyBaseClass_impl : MyBaseClass
{   }

public MyBaseClass CreateFromMetaData(string metaData)
{
    string className = "MyNamespace.MyBaseClass_" + metaData;
    Type t = System.Reflection.Assembly.GetExecutingAssembly().GetType(className, false);
    if (t != null)
    {
        return (MyBaseClass)Activator.CreateInstance(t);
    }

    return null;
}

Following this, using "impl" as the parameter for CreateFromMetaData would return a new MyBassClass_impl object, while any other string would return null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.