2

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!

Kyle Jurick
  • 244
  • 2
  • 15
  • "what is the best way to tell which interface the class I've instantiated subscribes to", what does this mean? – Matthew Jan 21 '13 at 14:49
  • you could also just store that information in the xml with the class name. – tallseth Jan 21 '13 at 14:52
  • Matthew, Ani's answer below took care of it. Thanks for your help! – Kyle Jurick Jan 21 '13 at 14:55
  • I am storing it with the class name, but that class could be subscribing to two different interfaces. I could store the interfaces it uses, but that would require the person altering the XML file to have a better understanding of how my code works, something I don't have the luxury of. – Kyle Jurick Jan 21 '13 at 14:56

1 Answers1

5

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);
Ani
  • 111,048
  • 26
  • 262
  • 307
  • Yes, I think you hit the nail on the head. Just as I saw your answer I found this which is similar http://stackoverflow.com/questions/410227/test-if-object-implements-interface Thanks for your help! – Kyle Jurick Jan 21 '13 at 14:52