Introduction
This article shows how to get all the types a COM object implements.
Background
When you get a COM object in C#, if you know the classes and the interfaces it implements, you can easily cast it to the desired type. But, what if you don't know its type. Or more to the point, you think you know it's type and it doesn't implement that type.
Using the code
The following method will return all the types that a COM object implements. I don't use this in production code, but I do use it occasionally when writing code.
public static Type[] GetAllTypes(object comObject, Type assType)
{
IntPtr iunkwn = Marshal.GetIUnknownForObject(comObject);
Assembly interopAss = Assembly.GetAssembly(assType);
Type[] excelTypes = interopAss.GetTypes();
ArrayList implTypes = new ArrayList();
foreach (Type currType in excelTypes)
{
Guid iid = currType.GUID;
if (!currType.IsInterface || iid == Guid.Empty)
continue;
IntPtr ipointer;
Marshal.QueryInterface(iunkwn, ref iid, out ipointer);
if (ipointer != IntPtr.Zero)
implTypes.Add(currType);
}
return (Type[])implTypes.ToArray(typeof(Type));
}
History
Original post.