Indexed Property Design
Indexed properties allow array-like access to groups of items (for example, the characters in a string or the bits in a). Indexed properties, called indexers or default properties, differ from regular properties in that they take parameters indicating which element in the group to access. The implementation of an index property should be as simple as possible because indexers are often used in loops. The following guidelines help ensure that your types contain well-designed indexes where appropriate.
Consider using indexers to provide access to data stored in an internal array.
Consider providing indexers on types representing collections of items.
Avoid indexed properties with more than one parameter.
If an indexer requires multiple parameters, reevaluate whether the property really represents access to a logical collection. If not, use methods instead and consider choosing a method name that begins with Get or Set.
Avoid indexers with parameter types other than System.Int32, System.Int64, System.String, System.Object, enumerations, or generic type parameters.
If the design requires other types of parameters, you should strongly reevaluate whether the member really represents access to a logical collection. If not, use methods instead and consider choosing a method name that begins with Get or Set.
Do use the name Item for indexed properties unless there is an obviously better name (for example, see the System.String.Chars(System.Int32) property).
Theattribute can be used to customize the name of an indexer.
Do not provide both an indexer and methods that are semantically equivalent.
In the following code example, the indexer should be changed to a method.
Do not provide more than one family of overloaded indexers in one type.
Some compilers, such as the C# compiler, enforce this guideline.
Multiple sets of indexers are not supported by some languages. If you use them, some developers will not be able to access these members.
Do not use non-default indexed properties.
Some compilers, such as the C# compiler, enforce this guideline. Non-default indexed properties are not supported in all programming languages. If you use them, some developers will not be able to access these members.
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.