title: Passing a C# class instance back to managed code from JavaScript via COM
body: <p>The basic outline of my problem is shown in the code below.  I'm hosting a WebBrowser control in a form and providing an <code>ObjectForScripting</code> with two methods: <code>GiveMeAGizmo</code> and <code>GiveMeAGizmoUser</code>.  Both methods return the respective class instances:</p>
  
  <pre class="lang-c# prettyprint-override"><code>[ComVisible]
  public class Gizmo
  {
      public string name { get; set; }
  }
  
  [ComVisible]
  public class GizmoUser
  {
      public void doSomethingWith(object oGizmo)
      {
          Gizmo g = (Gizmo) oGizmo;
          System.Diagnostics.Debug.WriteLine(g.name);
      }
  }
  </code></pre>
  
  <p>In JavaScript, I create an instance of both classes, but I need to pass the first instance to a method on the second instance.  The JS code looks a little like this:</p>
  
  <pre class="lang-js prettyprint-override"><code>var 
      // Returns a Gizmo instance
      gizmo = window.external.GiveMeAGizmo(),
  
      // Returns a GizmoUser instance
      gUser = window.external.GiveMeAGizmoUser();
  
  gizmo.name = 'hello';
  
  // Passes Gizmo instance back to C# code
  gUser.doSomethingWith(gizmo);
  </code></pre>
  
  <p>This is where I've hit a wall.  My C# method <code>GizmoUser.doSomethingWith()</code> cannot cast the object back to a Gizmo type.  It throws the following error:</p>
  
  <blockquote>
    <p>Unable to cast COM object of type 'System.__ComObject' to interface type 'Gizmo'</p>
  </blockquote>
  
  <p>Unsure how to proceed, I tried a couple of other things:</p>
  
  <ul>
  <li>Safe casting <code>Gizmo g = oGizmo as Gizmo;</code> (<code>g</code> is <code>null</code>)</li>
  <li>Having the classes implement <code>IDispatch</code> and calling <code>InvokeMember</code>, as <a href="https://stackoverflow.com/a/2152193/94197">explained here</a>.  The member "name" is <code>null</code>.</li>
  </ul>
  
  <p>I need this to work with .NET framework version lower than 4.0, so I cannot use <code>dynamic</code>.  Does anybody know how I can get this working?</p>