Indexed properties improve the way in which COM properties that have parameters are consumed in C# programming. Indexed properties work together with other features introduced in Visual C# 2010, 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, introduced in Visual C# 2010, which enables you to omit Type.Missing. |
Similarly, to set the value of the Value property of a Range object in Visual C# 2008 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. Before Visual C# 2010, C# allowed only one argument. Therefore, instead of using a regular set method, you had to either use the set_Value method or a different property, Value2. 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.