Thursday, May 5, 2011

Unable to cast COM object of type 'System.__ComObject' to class type .......

Unable to cast COM object of type 'System.__ComObject' to class type '...your dotnet class'. COM components that enter the CLR and do not support IProvideClassInfo or that do not have any interop assembly registered will be wrapped in the __ComObject type. Instances of this type cannot be cast to any other class; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.

This is a very common error if you are working with dot net interop. This is generally come when you try to typecast the com object(RCW) to the coclass object created by the interop. for example -

MyServerClass = (MyServerClass )Activator.CreateInstance(type representing my com server);

dotnet does not allow you to typecast it directly to coclass object. however it allow you to typecast to any interface it has implemented. As it can internally QueryInterface for any interface it has implemented. To resolve this you should type cast to Intterface. like -

IMyServer = (IMyServer)Activator.CreateInstance(type representing my com server);

The above technique should solve your problem. For more depth knowledge you can refer following links.

http://edndoc.esri.com/arcobjects/9.1/ArcGISDevHelp/DevelopmentEnvs/DotNet/SystemComObject.htm

To know how to create DCOM object from dotnet you can refer following articles -

http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0bfcafa2-1c64-442d-9d45-7ceeade2b6b3/

Hope this will be helpful for someone.