<p>I'm trying to wrap my head around reflection, so I decided to add plugin capability to a program that I'm writing. The only way to understand a concept is to get your fingers dirty and write the code, so I went the route of creating a simple interface library consisting of the IPlugin and IHost interfaces, a plugin implementation library of classes that implement IPlugin, and a simple console project that instantiates the IHost implementation class that does simple work with the plugin objects. </p>

<p>Using reflection, I wanted to iterate through the types contained inside my plugin implementation dll and create instances of types.  I was able to sucessfully instantiate classes with this code, but I could not cast the created object to the interface.</p>

<p>I tried this code but I couldn't cast object o as I expected. I stepped through the process with the debugger and the proper constructor was called. Quickwatching object o showed me that it had the fields and properties that I expected to see in the implementation class. </p>

<pre><code>loop through assemblies
  loop through types in assembly
    // Filter out unwanted types
    if (!type.IsClass || type.IsNotPublic || type.IsAbstract )
      continue;
    // This successfully created the right object
    object o = Activator.CreateInstance(type);
    // This threw an Invalid Cast Exception or returned null for an "as" cast
    // even though the object implemented IPlugin      
    IPlugin i = (IPlugin) o;
</code></pre>

<p>I made the code work with this.</p>

<pre><code>using System.Runtime.Remoting;
ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName);
// This worked as I intended
IPlugin i = (IPlugin) oh.Unwrap();
i.DoStuff();
</code></pre>

<p>Here are my questions:</p>

<ol>
<li>Activator.CreateInstance(Type t) returns an object, but I couldn't cast the object to an interface that the object implemented. Why?</li>
<li>Should I have been using a different overload of CreateInstance()?</li>
<li>What are the reflection related tips and tricks?</li>
<li>Is there some crucial part of reflection that I'm just not getting? </li>
</ol>

[{'answer_id': 31576, 'author': 'Haacked', 'author_id': 598, 'author_profile': 'https://Stackoverflow.com/users/598', 'pm_score': 0, 'selected': False, 'text': '<p>Is your type not public, if so, call the overload that takes in a boolean:</p>\n\n<pre><code>Activator.CreateInstance(type, true);\n</code></pre>\n\n<p>Also, in your first example, see if o is null and if not, print out o.GetType().Name to see what it really is.</p>\n'}, {'answer_id': 31617, 'author': 'Ben Robbins', 'author_id': 1880, 'author_profile': 'https://Stackoverflow.com/users/1880', 'pm_score': 0, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/31567/how-to-properly-cast-objects-created-through-reflection#31576">Haacked</a></p>\n\n<p>I tried to keep the pseudocode simple. foreach\'s take up a lot of space and braces. I clarified it.</p>\n\n<p>o.GetType().FullName returns Plugins.Multiply which is the expected object. Plugins.Multiply implements IPlugin. I stepped through the process in the debugger quite a few times until I gave up for the evening. Couldn\'t figure out why I couldn\'t cast it because I watched the constructor fire until I got grumpy about the whole mess. Came back to it this evening and made it work, but I still don\'t understand why the cast failed in the first code block. The second code block works, but it feels off to me. </p>\n'}, {'answer_id': 31638, 'author': 'lubos hasko', 'author_id': 275, 'author_profile': 'https://Stackoverflow.com/users/275', 'pm_score': 3, 'selected': True, 'text': "<p>I'm just guessing here because from your code it's not obvious where do you have definition of IPlugin interface but if you can't cast in your host application then you are probably having IPlugin interface in your host assembly and then at the same time in your plugin assembly. This won't work.</p>\n\n<p>The easiest thing is to make this work is to have IPlugin interface marked as public in your host assembly and then have your Plugin assembly <strong>reference host application assembly</strong>, so both assemblies have access to <strong>the very same interface</strong>.</p>\n"}, {'answer_id': 33669, 'author': 'Ben Robbins', 'author_id': 1880, 'author_profile': 'https://Stackoverflow.com/users/1880', 'pm_score': 1, 'selected': False, 'text': '<p>@<a href="https://stackoverflow.com/questions/31567/how-to-properly-cast-objects-created-through-reflection#31638">lubos hasko</a></p>\n\n<p>You nailed it on the nose. My original design did have three different assemblies with both the host and plugin implementation referencing the plugin interface assembly. </p>\n\n<p>I tried a separate solution with a host implementation and interface assembly and a plugin implementation assembly. Within that solution, the code in the first block worked as expected. </p>\n\n<p>You\'ve given me a bit more to think about, because I\'m not quite understanding why two assemblies referencing a common assembly don\'t get the same type out of the common assembly. </p>\n'}, {'answer_id': 178205, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': "<p>I was just trying to work this out myself and managed to stumble on the answer!</p>\n\n<p>I had 3 different C# projects</p>\n\n<ul>\n<li>A - Plugin Interface project</li>\n<li>B - Host exe project -> references A</li>\n<li>C - Plugin Implementation project -> references A</li>\n</ul>\n\n<p>I was getting the casting error as well until I changed the assembly name for my Plugin Interface proj to match the namespace of what I was trying to cast to.</p>\n\n<p>E.g.</p>\n\n<pre><code>IPluginModule pluginModule = (IPluginModule)Activator.CreateInstance(curType);\n</code></pre>\n\n<p>was failing because the assembly that the IPluginModule interface was defined in was called 'Common', The -type- I was casting to was 'Blah.Plugins.Common.IPluginModule' however.</p>\n\n<p>I changed the Assembly name for the interface proj to be 'Blah.Plugins.Common' meant that the cast then succeeded.</p>\n\n<p>Hopefully this explanation helps someone. Back to the code..</p>\n"}, {'answer_id': 178282, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 2, 'selected': False, 'text': '<p>hmmm... If you are using Assembly.LoadFrom to load your assembly try changing it Assembly.LoadFile instead.</p>\n\n<p>Worked for me</p>\n\n<p>From here: <a href="http://www.eggheadcafe.com/community/aspnet/2/10036776/solution-found.aspx" rel="nofollow noreferrer">http://www.eggheadcafe.com/community/aspnet/2/10036776/solution-found.aspx</a></p>\n'}, {'answer_id': 4808577, 'author': 'Robel Robel Lingstuyl', 'author_id': 591115, 'author_profile': 'https://Stackoverflow.com/users/591115', 'pm_score': 0, 'selected': False, 'text': '<p>The link to egghead above is the main solution to the problem use Assembly.LoadFile() instead of .LoadFrom()</p>\n'}]
['https://Stackoverflow.com/questions/31567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880/']