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.
Back to the top
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 |
Back to the top
Declare an object of type "Missing"
object m = Type.Missing;
Back to the top
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);
Back to the top
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; |
Back to the top
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;
Back to the top