Reputation: 12170
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:
try-catch
block handle it?Upvotes: 1
Views: 7565
Reputation: 12170
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.
Upvotes: 1
Reputation: 8283
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.
Upvotes: 4