Skip to main content

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# :)









Comments