I am interested in the possibilities offered by the C# dynamic keyword, but I am facing unexpected issues.
If I create a default .NET 4.8 template in Visual Studio 2022...
This works:
dynamic obj = Marshal.GetActiveObject("Excel.Application");
obj.Workbooks.Add();
This works too:
object obj1 = Marshal.GetActiveObject("FancySoft.Application");
object obj2 = obj1.GetType().InvokeMember("FancyProperty", BindingFlags.GetProperty, null, obj1, null);
This fails with a System.Runtime.InteropServices.COMException: 'Error HRESULT E_FAIL has been returned from a call to a COM component.':
dynamic obj1 = Marshal.GetActiveObject("FancySoft.Application");
object obj2 = obj1.FancyProperty;
Finally, if I add a COM reference to FancySoft to my project, this works as expected:
var obj1 = (Application) Marshal.GetActiveObject("FancySoft.Application");
var obj2 = obj1.FancyProperty;
I have found an interesting discussion thread that suggests that a Vendor can intentionally restrict the use of the dynamic keyword in client applications.
In my case, the Vendor doesn't even officially support .NET-based automation scenario (although it is a common scenario in our industry) so I can't ask them for that type of information.
Have you seen this behavior elsewhere? Am I missing something? Is there any way to confirm that this behavior is intentional without asking the vendor? (By looking at the .TLB files, using some reflection tricks, etc.?)
dynamicmostly (it not entirely) usesIDispatch("aka late binding" which is name-based), and yes this is completely possible that it doesn't work. I doubt it's intentional, more a bad interface design, as demonstrated in other post stackoverflow.com/questions/77478817/…