title: Can the usage of a "handle" help to prevent a "System.InvalidCastException"?
body: <p>I just started to program with C#, so my problem might be due to my lack of knowledge.</p>
  
  <p>I am trying to control a scientific experimental device with my C# program. The producer of the device provides an ActiveX API that contains all the classes and methods that should be needed in order to control the device.
  The basic idea of the initialization process is like this: </p>
  
  <ol>
  <li>create object1 of kind class1</li>
  <li>run object1.initialize() method (returns an int = 0 if successful)</li>
  <li>run object1.detect() method (returns an int = 0 if successful)</li>
  <li>run object1.getInterface(string serialNo) method (should return an object of kind class2 that is needed for further controlling)</li>
  </ol>
  
  <p>My problem is in step 4. In the "Object browser" of Microsoft Visual Studio 2010 it says for this method:</p>
  
  <pre><code>public virtual class2 getInterface(string serialNo)
  </code></pre>
  
  <p>So I first assumed that this kind of code should work:</p>
  
  <pre><code>public class1 object1 = new class1();
  public class2 object2;
  
  public void initialize()
  {
   int initInt = object1.initialize();
   int devInt = object1.detect();
   string serialNo = object1.DeviceList[0].ToString(); 
  // I am able to read this string and it is the correct serial number!
   object2 = object1.getInterface(serialNo);
  </code></pre>
  
  <p>But when running the program this leads to "System.InvalidCastException" and my object2 remains null.</p>
  
  <p>In the user manual for this API the producer of the device says about this "getInterface(string)" function that it returns a handle to a device sub-object. 
  As definition it further says (I don't know which kind of language):</p>
  
  <pre><code>class2 *getInterface(BSTR serialNo)
  </code></pre>
  
  <p>I looked a bit for handles in C# but I am always mixing up handles, pointers and references. Maybe you could give some page where to study the differences of these in an easy way?</p>
  
  <p>Further I am looking for tips how I could try to create my object2 without having the InvalidCastException. How do I use a handle? Or should I use a pointer?</p>
  
  <p>Thanks a lot for your help!</p>
  
  <p>Edit: The whole message of the exception is:</p>
  
  <pre><code>System.InvalidCastException: Return argument has an invalid type. at System.Runtime.Remoting.Proxies.RealProxy.ValidateReturnArg(Object arg, Type paramType) at
  System.Runtime.Remoting.Proxies.RealProxy.PropagateOutParameters(IMessage msg, Object[] outArgs, Object returnValue)
  at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData&amp; msgData)
  at thUsedCOMLib.class1.getInterface(String serialNo) at MyProject.Form1.initialize() in path/to/my/file.cs:line 00
  </code></pre>