2

I'm not a C# programmer so excuse me if it's a silly question, but I can't find any solutions.

I have an Object. It's a COM object and its ToString() returns "System.__comObject". When examining its inner contents with debugger I can see that this object has a property called Object and it's an instance of the actual class that I want. However, Object class has no property Object, and when I'm trying to cast the object itself to the desired type I get an exception. How should COM object be converted to a .NET object?

5
  • You can't, the best you can do is cast it to an interface that matches one of the COM interfaces that object implements Commented Oct 7, 2013 at 14:14
  • @Mgetz: how can I found what interfaces it implements? Commented Oct 7, 2013 at 14:15
  • Your question seems to indicate you have access to the native code, if that's the case you can look at the objects native declaration. But if you can I would highly suggest using Tlbimp to create a .NET library to do the interop for you. Commented Oct 7, 2013 at 14:18
  • @Mgetz: no, it's Microsoft library and it's very poorly documented. I certainly don't have the declaration for this object. In fact, I can only guess it's type, which is exactly what I'm trying to do. Commented Oct 7, 2013 at 14:21
  • Which library? It may already have a Primary Interop Assembly. Commented Oct 7, 2013 at 14:21

1 Answer 1

3

If you know what type you'd like it to be, you could set up a method to convert it yourself, using dynamic to access the properties:

public static MyObject ConvertFromComObject(dynamic comObject)
{
    return comObject.Object;
}
// or, if that doesn't work:
public static MyObject ConvertFromComObject(dynamic comObject)
{
    return new MyObject { MyProperty = comObject.Object.MyProperty };
}
// or maybe
public static MyObject ConvertFromComObject(dynamic comObject)
{
    return new MyObject { MyProperty = comObject.MyProperty };
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works, thanks a lot! Can I make it work in-line, without a standalone method?
@VioletGiraffe Yes of course. Just cast to dynamic, e.g. MyObject myObj = ((dynamic)comObject).Object;, or declare your comObject as dynamic from the start: dynamic comObject = SomeCom.GetObject(); comObject.Object.DoSomething();.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.