COM component when used in C# causes InvalidCastException

187 views Asked by At

i have a COM component, we have created a interop dll using TLBIMP tool and when accesing the default interface, it sometimes fails with InvalidCastException (Unable to cast COM object of type System.__ComObject’ )

private void SomeMethod(IMyInterface iObj)
 {
      **//Following cause error InvalidCastException, not always but Intermittently**
      //MyComponent comp = new MyComponentClass();    
      //comp= iObj as MyComponent


      **//The below code works fine.**
      IMyInterface comp = new MyComponentClass();
      comp = iObj;
}

IDL declaration

  coclass MyComponent
   {
      [default] interface IMyInterface;
   };

any idea why the commented code in the above function fails with the error ? also the line MyComponent comp = new MyComponentClass() should be returning the default interface, in that case shouldn't the LHS variable be of type interface.

1

There are 1 answers

0
Rÿck Nöthing On

This MSDN blog describes a similar error and provides some details about how that situation can happen: https://social.msdn.microsoft.com/Forums/vstudio/en-US/b11a0f90-fcc5-487a-b057-632f5415bfc2/problems-with-primary-interop-assembly-versioning?forum=csharpgeneral

Also, this is probably worth reading: http://blogs.agi.com/engine/?p=502