Violet Giraffe
Violet Giraffe

Reputation: 33579

Casting generic COM object to a specific .NET class

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?

Upvotes: 2

Views: 5395

Answers (1)

Tim S.
Tim S.

Reputation: 56536

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 };
}

Upvotes: 3

Related Questions