How to use indexed properties in COM interop programming (C# Programming Guide)

Indexed properties improve the way in which COM properties that have parameters are consumed in C# programming. Indexed properties work together with other features in Visual C#, such as named and optional arguments, a new type (dynamic), and embedded type information, to enhance Microsoft Office programming.

In earlier versions of C#, methods are accessible as properties only if the get method has no parameters and the set method has one and only one value parameter. However, not all COM properties meet those restrictions. For example, the Excel Range[] property has a get accessor that requires a parameter for the name of the range. In the past, because you could not access the Range property directly, you had to use the get_Range method instead, as shown in the following example.

// Visual C# 2008 and earlier.
var excelApp = new Excel.Application();
// . . .
Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing);


Indexed properties enable you to write the following instead:

// Visual C# 2010.
var excelApp = new Excel.Application();
// . . .
Excel.Range targetRange = excelApp.Range["A1"];


Note

The previous example also uses the optional arguments feature, which enables you to omit Type.Missing.

Similarly to set the value of the Value property of a Range object in C# 3.0 and earlier, two arguments are required. One supplies an argument for an optional parameter that specifies the type of the range value. The other supplies the value for the Value property. The following examples illustrate these techniques. Both set the value of the A1 cell to Name.

// Visual C# 2008.
targetRange.set_Value(Type.Missing, "Name");
// Or
targetRange.Value2 = "Name";


Indexed properties enable you to write the following code instead.

// Visual C# 2010.
targetRange.Value = "Name";


You cannot create indexed properties of your own. The feature only supports consumption of existing indexed properties.

Example

The following code shows a complete example. For more information about how to set up a project that accesses the Office API, see How to access Office interop objects by using C# features.

// You must add a reference to Microsoft.Office.Interop.Excel to run
// this example.
using System;
using Excel = Microsoft.Office.Interop.Excel;

namespace IndexedProperties
{
class Program
{
static void Main(string[] args)
{
CSharp2010();
//CSharp2008();
}

static void CSharp2010()
{
var excelApp = new Excel.Application();
excelApp.Visible = true;

Excel.Range targetRange = excelApp.Range["A1"];
targetRange.Value = "Name";
}

static void CSharp2008()
{
var excelApp = new Excel.Application();