How to pass optional method arguments from C#

Summary

This step-by-step article shows you how to take advantage of optional method arguments. C# does not support optional method arguments. However, there may be times when you are using components that were created in a language that supports optional arguments, such as legacy COM components or components created with Microsoft Visual Basic .NET.


For the purpose of illustration, the Navigate2 method of SHDocVw.IWebBroswer2 is used. Only the first of the five arguments to this method is required; the remaining four are optional.

Requirements

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
  • Microsoft Visual C# 2008
  • Microsoft Visual C# 2005
  • Microsoft Visual C# .NET

Declare an object of type "Missing"

 object m = Type.Missing;

Pass the "Missing" object as an argument

The Navigate2 method requires that arguments be passed by reference. Check the documentation for the method that you are using to determine if the arguments need to passed by value or by reference.
ie.Navigate2(ref url,ref m,ref m,ref m,ref m);

Set project references (optional)

The code sample in the "Complete code sample" section is used to illustrate this technique. This code sample does not run as is. If you want to try this code, you have to perform two additional steps:
  1. Add a project reference to Shdocvw.dll. This is listed as Microsoft Internet Controls in the COM section of the Add Reference dialog box.
  2. Precede the class declaration in your code with the following:
    using SHDocVw;

Complete code sample

   object m = Type.Missing;
object url = "http://www.microsoft.com";
InternetExplorer ie = new InternetExplorer();
ie.Navigate2(ref url,ref m,ref m,ref m,ref m);
ie.Visible = true;
Proprietăți

ID articol: 305814 - Ultima examinare: 16 iul. 2008 - Revizie: 1

Feedback