C# COM interop and optional parameters

By | July 18, 2010

Since C# supports optional paramters it is much easier to work with COM objects.
Sometimes you don’t want to set every parameter when you call a method from a COM object.

Let’s take the “Office Word” object for this easy example. The following C# 3.5 code creates a Office Word object and opens the document “test-document.docx”.

var appWord = new Application();
appWord.Visible = true;
object objMissing = Missing.Value;
object strFilename = @"C:\test-document.docx";
appWord.Documents.Open(ref strFilename, ref objMissing, 
         ref objMissing, ref objMissing, ref objMissing, 
         ref objMissing, ref objMissing, ref objMissing, 
         ref objMissing, ref objMissing, ref objMissing, 
         ref objMissing, ref objMissing, ref objMissing, 
         ref objMissing, ref objMissing);

As you see, you have to define for every parameter you don’t need a reference to an “Missing”-object.
And here the same example but in C# 4.0.

            var appWord = new Application();
            appWord.Visible = true;
            appWord.Documents.Open(@"C:\test-document.docx");

Which code is better? 😉

More about optional parameters here