How to: Use Named and Optional Arguments in Office Programming (C# Programming Guide)

Named arguments and optional arguments, introduced in Visual C# 2010, enhance convenience, flexibility, and readability in C# programming. In addition, these features greatly facilitate access to COM interfaces such as the Microsoft Office automation APIs.

In the following example, method ConvertToTable has sixteen parameters that represent characteristics of a table, such as number of columns and rows, formatting, borders, fonts, and colors. All sixteen parameters are optional, because most of the time you do not want to specify particular values for all of them. However, without named and optional arguments, a value or a placeholder value has to be provided for each parameter. With named and optional arguments, you specify values only for the parameters that are required for your project.

You must have Microsoft Office Word installed on your computer to complete these procedures.

Note

Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. The Visual Studio edition that you have and the settings that you use determine these elements. For more information, see Visual Studio Settings.

To create a new console application

  1. Start Visual Studio.

  2. On the File menu, point to New, and then click Project.

  3. In the Templates Categories pane, expand Visual C#, and then click Windows.

  4. Look in the top of the Templates pane to make sure that .NET Framework 4 appears in the Target Framework box.

  5. In the Templates pane, click Console Application.

  6. Type a name for your project in the Name field.

  7. Click OK.

    The new project appears in Solution Explorer.

To add a reference

  1. In Solution Explorer, right-click your project's name and then click Add Reference. The Add Reference dialog box appears.

  2. On the .NET page, select Microsoft.Office.Interop.Word in the Component Name list.

  3. Click OK.

To add necessary using directives

  1. In Solution Explorer, right-click the Program.cs file and then click View Code.

  2. Add the following using directives to the top of the code file.

    using Word = Microsoft.Office.Interop.Word;
    

To display text in a Word document

  1. In the Program class in Program.cs, add the following method to create a Word application and a Word document. The Add method has four optional parameters. This example uses their default values. Therefore, no arguments are necessary in the calling statement.

    static void DisplayInWord()
    {
        var wordApp = new Word.Application();
        wordApp.Visible = true;
        // docs is a collection of all the Document objects currently 
        // open in Word.
        Word.Documents docs = wordApp.Documents;
    
        // Add a document to the collection and name it doc. 
        Word.Document doc = docs.Add();
    }
    
  2. Add the following code at the end of the method to define where to display text in the document, and what text to display.

    // Define a range, a contiguous area in the document, by specifying
    // a starting and ending character position. Currently, the document
    // is empty.
    Word.Range range = doc.Range(0, 0);
    
    // Use the InsertAfter method to insert a string at the end of the
    // current range.
    range.InsertAfter("Testing, testing, testing. . .");
    

To run the application

  1. Add the following statement to Main.

    DisplayInWord();
    
  2. Press CTRL+F5 to run the project. A Word document appears that contains the specified text.

To change the text to a table

  1. Use the ConvertToTable method to enclose the text in a table. The method has sixteen optional parameters. IntelliSense encloses optional parameters in brackets, as shown in the following illustration.

    ConvertToTable parameters

    List of parameters for ConvertToTable method.

    Named and optional arguments enable you to specify values for only the parameters that you want to change. Add the following code to the end of method DisplayInWord to create a simple table. The argument specifies that the commas in the text string in range separate the cells of the table.

    // Convert to a simple table. The table will have a single row with
    // three columns.
    range.ConvertToTable(Separator: ",");
    

    In earlier versions of C#, the call to ConvertToTable requires a reference argument for each parameter, as shown in the following code.

    // Call to ConvertToTable in Visual C# 2008 or earlier. This code
    // is not part of the solution.
    var missing = Type.Missing;
    object separator = ",";
    range.ConvertToTable(ref separator, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing, ref missing, ref missing, ref missing,
        ref missing);
    
  2. Press CTRL+F5 to run the project.

To experiment with other parameters

  1. To change the table so that it has one column and three rows, replace the last line in DisplayInWord with the following statement and then type CTRL+F5.

    range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);
    
  2. To specify a predefined format for the table, replace the last line in DisplayInWord with the following statement and then type CTRL+F5. The format can be any of the WdTableFormat constants.

    range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
        Format: Word.WdTableFormat.wdTableFormatElegant);
    

Example

The following code includes the full example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;


namespace OfficeHowTo
{
    class WordProgram
    {
        static void Main(string[] args)
        {
            DisplayInWord();
        }

        static void DisplayInWord()
        {
            var wordApp = new Word.Application();
            wordApp.Visible = true;
            // docs is a collection of all the Document objects currently 
            // open in Word.
            Word.Documents docs = wordApp.Documents;

            // Add a document to the collection and name it doc. 
            Word.Document doc = docs.Add();

            // Define a range, a contiguous area in the document, by specifying
            // a starting and ending character position. Currently, the document
            // is empty.
            Word.Range range = doc.Range(0, 0);

            // Use the InsertAfter method to insert a string at the end of the
            // current range.
            range.InsertAfter("Testing, testing, testing. . .");

            // You can comment out any or all of the following statements to
            // see the effect of each one in the Word document.

            // Next, use the ConvertToTable method to put the text into a table. 
            // The method has 16 optional parameters. You only have to specify
            // values for those you want to change.

            // Convert to a simple table. The table will have a single row with
            // three columns.
            range.ConvertToTable(Separator: ",");

            // Change to a single column with three rows..
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1);

            // Format the table.
            range.ConvertToTable(Separator: ",", AutoFit: true, NumColumns: 1,
                Format: Word.WdTableFormat.wdTableFormatElegant);
        }
    }
}

See Also

Concepts

Named and Optional Arguments (C# Programming Guide)