title: Instantiating an Internal class and casting it as a given type
body: <p>Following up on <a href="https://stackoverflow.com/questions/3504257"> InternalsVisibleTo</a>. I have looked at <a href="https://stackoverflow.com/questions/2023193/c-instantiating-internal-class-with-private-constructor">c# Instantiating Internal class with private constructor</a>, and this has helped but I'm trying to cast the returned object as the internal type and, honestly I'm not 100% that that is possible.</p>
  
  <p>I'm trying the route of Reflection to fix this issue, but I'm having a tough time trying to figure out how to instantiate an internal type with private methods using reflection. I can go as far as pulling the type and getting the constructor and creating an object. </p>
  
  <p>How would I preform the cast of the object if the type I wish to cast is an internal type.?</p>
  
  <pre><code>public object InitPrivateCoreObjects(string Type)
  {
      Assembly Core = Assembly.Load("Stuff.Core, Version=0.3.3881.21340, Culture=neutral, PublicKeyToken=4fe470e63e2d354e");
      Type TypeToReflect = Core.GetType("Stuff.Core.AssemblyWithIdentifer");
      object o = Activator.CreateInstance(TypeToReflect);
      MethodInfo mi = TypeToReflect.GetMethod("AssemblyWithIdentifer");
      object newObject = mi.Invoke(o,null);
      //alternatively
      //ConstructorInfo ctor = TypeToReflect.GetConstructor(new Type[]{TypeToReflect.GetType()});
      //ctor.Invoke(newObject, null);
  
      return newObject;
  }
  </code></pre>
  
  <p>I can get the type of the internal class, <br />
  I can call the constructor and instantiate an object of the type. However, since I don’t have any access to the internal type I can’t cast it and manipulate it from there. </p>
  
  <p>I understand I can use <code>Reflection.Emit</code> to create a new class based on that type, but if I'm going that route then I might as well just copy the entire contents of the project I'm trying to access into my test project. This would be really wastefully and pointless and would require me to throw in stuff from other projects and creating a mess and it's absolutely not the route I want to go at this time.</p>
  
  <p>I've seen examples accessing individual methods and properties but none that instantiate an entire class. I'm not 100% sure it's possible since in the order of operations reflection happens before access modifiers are looked at. </p>
  
  <p>Can this be done, and if so, how?</p>
  
  <p>For clairification sake I wanted to use the instantiated object for testing purposes and <code>[Assembly:InternalsVisibleTo("")]</code> wasn't working due to bug which I'm currently working around. See <a href="https://stackoverflow.com/questions/3504257">here</a> for original question.</p>