Thursday, August 6, 2009

Getting Members of a System.__ComObject type

For C# ...

The problem: there is a dynamic parameter being passed into my function as an object, so I needed to use reflection to get a property from it. But here's the gotcha: the object is of type System.__ComObject! This sounds innoccuous, but getting members from this __ComObject can not be done directly. Here's the link where I found the info that fixed my problem:
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke(VS.85).aspx

And here's my summary:

Reflection (which is a way to access object properties and methods at runtime instead of at compilation) needs to use a Type to do its work. Like this:
Type myType = objectInQuestion.GetType();
PropertyInfo name = myType.GetProperty("Name"); //here's where the reflection happens.

BUT! This won't work if objectInQuestion is of type __ComObject.

So ... you have to work around this. Use the following:

string name = (string)objectInQuestion.GetType().InvokeMember("Name", BindingFlags.GetProperty, null, objectInQuestion, new Object[]{});

NOW name will be the Name property of objectInQuestion, as if you had been able to cast it in the first place. Don't ask me why this is so tricky, or why it was so hard to Google, but now it's done and I'm very happy.

No comments:

Post a Comment