Reputation: 242
I have a project I am working on that I would like to leverage Activator.createInstance with so that I can dynamically pull class names out of XML. The classes must subscribe to at least one of two interfaces depending on their functionality. My question is, when I use Activator.CreateInstance, what is the best way to tell which interface the class I've instantiated subscribes to? Should I wrap the cast in a try catch? It seems like that would be awful slow. Maybe I should cast it an obj and then call GetType and compare that to my interface names? Any help is appreciated!
Upvotes: 2
Views: 1393
Reputation: 113472
So you've already created the object? Then it's as simple as using as the is
operator.
var obj = Activator.CreateInstance(...);
bool objIsIMyInterface = obj is IMyInterface;
If you'd like to test at the point you've created a System.Type
, you can use Type.IsAssignableFrom
:
Type type = ...
bool typeIsIMyInterface = typeof(IMyInterface).IsAssignableFrom(type);
Upvotes: 5