title: How to properly cast objects created through reflection
body: <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>