65.9K
CodeProject is changing. Read more.
Home

Get rid of COM Interop DLL by using the new C# 4 dynamic keyword

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.88/5 (4 votes)

Jan 7, 2011

CPOL
viewsIcon

37650

How to instantiate a COM object wrapper and call a method at runtime

Up to now, to call a COM object from managed code, you had to either:

  • make a reference to the COM instance from your Visual Studio project (which means you had to have the COM object setup on your development machine)
  • or make a reference to a precompiled assembly containing your COM interop wrapper

With the new framework .NET and C# 4 comes the dynamic keyword that allows binding to an object's method at runtime using the underlying DLR.

So to make thing short, the only thing you've got to do to interop with a COM object is to instantiate it using an activator as a dynamic variable and call a runtime bound method on it, in two lines:

dynamic comInterop= Activator.CreateInstance(Type.GetTypeFromProgID("MyCOM.Object.Name"));
var result = comInterop.MethodCall(parameter);

Hope this helps! :-)