If the object being returned can be one of many Types then you're best to keep using it as a dynamic
and only trying to access methods and properties you know will exist (I'd expect the COM method to have some indication of how to use the dynamic it returns).
var canBeLiterallyAnything = ComMethod();
canbeLiterallyAnything.MethodDocsSayExists();
var propVal = canBeLiterallyAnything.SomeProperty;
Of course, if all of the possible Types all implement the same interface, you could cast to that interface.
var typeSafeReference = (ISharedInterface)canBeLiterallyAnything;
If you know that the COM method returns a specific Type but just don't know what that Type is then for the purpose of investigation you can call GetType() and either write it to console or set a breakpoint and inspect it. This will let you then update your code to include a cast to that Type (which would minimise the impact of the use of dynamic
, but also introduce the risk of a bad cast if other Types can be returned).
var type = canBeLiterallyAnything.GetType();
// e.g. If the above returns a Type of 'SpecificType', then you can update code to
var typeSafeReference = (SpecificType)canBeLiterallyAnything;
It should be noted that the COM method might not return a concrete Type, it might be returning an anonymous object, in which case there is no casting you can do so you'll have to just keep using it as a dynamic
and only access properties/methods you know exist.