[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]
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 C# 4.0, 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"];
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 must either use the set_Value method or a different property, Value2. The following example illustrates this technique. The example sets the value of the A1 cell to Name.
// Visual C# 2008.
targetRange.set_Value(Type.Missing, "Name");
Indexed properties enable you to write the following code instead.
// Visual C# 2010.
targetRange.Value = "Name";
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 Visual C# 2010 Features (C# Programming Guide).
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.Workbooks.Add();
excelApp.Visible = true;
Excel.Range targetRange = excelApp.Range["A1"];
targetRange.Value = "Name";
}
static void CSharp2008()
{
var excelApp = new Excel.Application();
excelApp.Workbooks.Add(Type.Missing);
excelApp.Visible = true;
Excel.Range targetRange = excelApp.get_Range("A1", Type.Missing);
targetRange.set_Value(Type.Missing, "Name");
}
}
}
Tasks
Reference
Concepts
Other Resources