Showing posts with label COM. Show all posts
Showing posts with label COM. Show all posts

Friday, October 8, 2010

Limitations of COM Interop

Following is the list of some shortcomings:

  • Static/shared members: COM objects are fundamentally different from .Net types. One of the differences is lack of support for static/shared members.
  • Parameterized Constructors: COM types don't allow parameters to be passed into a constructor. This limits the control you have over initialization and the use of overloaded constructors.
  • Inheritance: One of the biggest issues is the limitations COM objects place on the inheritance chain. Members that shadow members in a base class aren't recognizable, and therefore, aren't callable or usable in real sense.
  • Portability: Operating Systems other than Windows don't have registry. Reliance on Windows registry limits the number of environments a .Net application can be ported to.

Optional Parameter issue with COM and C#/VB

As we all know, C# doesn't support optional parameters(till framework 3.5) whereas VB does.In the same way, COM components don't support parameter overloading, so for each value in a parameter list, we've got to pass in something, even if it does nothing. Moreover, COM parameters are always passes by reference, which means we can't pass NULL as a value.


In VB 2005, this is not really as issue because it supports optional parameters and we can just leave them out. But C# doesn't support this, so one have to create object variables and pass them in.


See following code sample:
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;  // Must have office installed
Application NewExcelApp = new Application;
NewExcelApp.Worksheets.Add();       // This will not compile


So, as a workaround, the Type.Missing field can be used and this field can be passed in with the C# code and the application will work as expected. 


Check it in below code snippet:


using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;  // Must have office installed
private Object OptionalParamHandler = Type.Missing;
Application NewExcelApp = new Application;
NewExcelApp.Worksheets.Add(OptionalParamHandler ,OptionalParamHandler ,OptionalParamHandler ,OptionalParamHandler ); 

This approach allows your code to work in C# :)