15.8 Use Optional Parameters


Problem

You need to call a method in a COM component without supplying all the required parameters.

Solution

Use the Type.Missing field.

Discussion

The .NET Framework is designed with a heavy use of method overloading. Most methods are overloaded several times so that you can call the version that requires only the parameters you choose to supply. COM, on the other hand, doesn't support method overloading. Instead, COM components usually use methods with a long list of optional parameters. Unfortunately, C# doesn't support optional parameters, which means C# developers are often forced to supply numerous additional or irrelevant values when accessing a COM component. And because COM parameters are often passed by reference, your code can't simply pass a null referenceinstead, it must declare an object variable and then pass that variable.

You can mitigate the problem to some extent by supplying the Type.Missing field whenever you wish to omit an optional parameter. If you need to pass a parameter by reference, you can simply declare a single object variable, set it equal to Type.Missing , and use it in all cases, like this:

 private static object n = Type.Missing; 

The following example uses the Word COM objects to programmatically create and show a document. Many of the methods the example uses require optional parameters passed by reference. You'll notice that the use of the Type.Missing field simplifies this code greatly. Each use is emphasized in the code listing.

 using System; public class OptionalParameters {     private static object n = Type.Missing;     private static void Main() {         // Start Word in the background.         Word.ApplicationClass app = new Word.ApplicationClass();         app.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone;                      // Create a new document (this is not visible to the user).         Word.Document doc = app.Documents.Add(  ref n  ,  ref n  ,  ref n  ,  ref n  );         Console.WriteLine();         Console.WriteLine("Creating new document.");         Console.WriteLine();         // Add a heading and two lines of text.         Word.Range range = doc.Paragraphs.Add(  ref n  ).Range;         range.InsertBefore("Test Document");         string style = "Heading 1";         object objStyle = style;         range.set_Style(ref objStyle);                      range = doc.Paragraphs.Add(  ref n  ).Range;         range.InsertBefore("Line one.\nLine two.");         range.Font.Bold = 1;         // Show a print preview, and make Word visible.         doc.PrintPreview();         app.Visible = true;         Console.ReadLine();     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net