C# Interop Implementation within .NET Framework

There are several reasons .NET Framework accommodates interoperability between old and new technologies. First, many companies have extensive libraries of legacy code that they cannot simply rework into new libraries as a result a mechanism that allow to bridge old legacy code with new applications requires. Second, many companies trying to do migration one piece at a time as a result there is a need to integrate existing libraries with new libraries while migrating entire application. Windows based libraries of the past relied mostly on COM architecture and as a result interoperability was designed to bridge .NET framework and COM specifically. This bridge is the Runtime Callable Wrapper (RCW) which helps to marshal data, handle interfaces and events.

We can import libraries via Visual Studio 2005 via Add Reference option that provides us with the tab called COM and the list of all registered COM components available. Alternatively we can use TlbImp.exe. There is one important thing to remember, COM does not allow parameter overloading, so you need to pass all COM parameters and since they use references, null cannot be passed. In C# we need to create object variables and then pass them or the better way is to use Type.Missing field instead.

class Program
        private static Object OptionalParamHandler = Type.Missing;
        static void Main(string[] args)
            Application NewExcelApp = new Application();
            NewExcelApp.Worksheets.Add(ref OptionalParamHandler,
                ref OptionalParamHandler, ref OptionalParamHandler,
                ref OptionalParamHandler);

There are many tools that allow .NET Framework to work with COM


NameApplication Name
Type Library Importer TlbImp.exe
Type Library Exporter TlbExp.exe
Registry Editor Regedit.exe
Intermediate Language Disassembler Ildasm.exe
Assembly Registration Tool Regasm.exe

Example of COM usage within .NET Code


If we need to handle COM Exceptions we need to employ RuntimeWrappedException class with following Properties


Data Collection of key/value pairs
HelpLink Sets a link to the help file
InnerException Manages the Exception
Message Manages a message about exception
Source Manages or sets the name of the application
StackTrace Manages a string representation of the frames
TargetSite Manages the method that throws the current exception
WrappedException Manages the object that was wrapped by the RuntimeWrappedException

There are several limitations in COM Interop .NET Framework

  • No support for static or shared members
  • COM does not allow parameterized constructors
  • Limits in using inheritance
  • Non Windows OS don’t have registries that limits .NET environments