Optional Parameter Issue With COM in C#

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

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

See the 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 the following 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#. :)


Similar Articles