Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Get all the types a COM object implements

0.00/5 (No votes)
17 Feb 2009 2  
How to return all types that a COM object implements.

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.

/// <summary>
/// Get all implemented types in a COM object. Code based on work at
/// http://fernandof.wordpress.com/2008/02/05/how-to-check-
///          the-type-of-a-com-object-system__comobject-with-visual-c-net/
/// </summary>
/// <param name="comObject">The object we want all types of.</param>
/// <param name="assType">Any type in the COM assembly.</param>
/// <returns>All implemented classes/interfaces.</returns>
public static Type[] GetAllTypes(object comObject, Type assType)
{

    // get the com object and fetch its IUnknown
    IntPtr iunkwn = Marshal.GetIUnknownForObject(comObject);

    // enum all the types defined in the interop assembly
    Assembly interopAss = Assembly.GetAssembly(assType);
    Type[] excelTypes = interopAss.GetTypes();

    // find all types it implements
    ArrayList implTypes = new ArrayList();
    foreach (Type currType in excelTypes)
    {
        // com interop type must be an interface with valid iid
        Guid iid = currType.GUID;
        if (!currType.IsInterface || iid == Guid.Empty)
        continue;

        // query supportability of current interface on object
        IntPtr ipointer;
        Marshal.QueryInterface(iunkwn, ref iid, out ipointer);

        if (ipointer != IntPtr.Zero)
          implTypes.Add(currType);

        }

    // no implemented type found
    return (Type[])implTypes.ToArray(typeof(Type));
}

History

Original post.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here