Casting a System.__ComObject in C# via reflection

c#

Solution

In general, no.

The _ComObject needs to implement an interface which the .Net runtime knows about. This will either be an interface which you get from `QueryInterface` or `IDispatch`.

If it's the former, you have to know what the interface is, and then you have to describe the interface to .Net using the ComImportAttribute on the interface.

If the COM object implements `IDispatch`, you can dynamically invoke members on it. In .Net 4.0 and above, this can be done easily by using the `dynamic` keyword. If you are using an earlier version of .Net, you can call `InvokeMember()` on the type returned by `GetType()` or else cast to `IReflect` and use that interface to call methods.

The best case is if you get a Runtime Callable Wrapper (RCW) for the COM object, either by running `tlbimp.exe` yourself on the COM library or getting a Primary Interop Assembly (PIA) for it, usually from the COM library author.

Problem

I'm attempting to cast a `System.__ComObject` to an interface type using reflection. I have tried using `Convert.ChangeType(Object,Type)` but c# then throws this error: System.InvalidCastException: Object must implement IConvertible. So is there any possible way to cast a general `__ComObject` using reflection to its correct type so i can then call its methods via reflection? And yes, it has to be done via a method which doesn't involve telling the compiler ahead of time what the object type is!

Original source