C Sharp

Design Guidelines

Indexers are yet another example of the C# design team adding a subtle yet powerful feature to the language to help us become more productive in our development endeavors. However, like any feature of any language, indexers have their place. They should be used only where it would be intuitive to treat an object like an array. Let's take as an example the case of invoicing. It's reasonable that an invoicing application has an Invoice class that defines a member array of InvoiceDetail objects. In such a case, it would be perfectly intuitive for the user to access these detail lines with the following syntax: -

InvoiceDetail detail = invoice[2]; // Retrieves the 3rd detail line.

However, it wouldn't be intuitive to take that a step further and try to turn all of the InvoiceDetail members into an array that would be accessed via an indexer. As you can see here, the first line is much more readily understood than the second: -

TermCode terms = invoice.Terms; // Property accessor to Terms member.
TermCode terms = invoice[3];    // A solution in search of a problem.

In this case, the maxim holds true that just because you can do something doesn't mean you should necessarily do it. Or, in more concrete terms, think of how implementing any new feature is going to affect your class's clients, and let that thinking guide you when you're deciding whether implementing the feature will make the use of your class easier.


C# properties consist of field declaration and accessor methods. Properties enable smart access to class fields so that a programmer writing a client for the class doesn't have to try to determine whether (and how) an accessor method for the field was created. Arrays in C# are declared by placing an empty square bracket between the type and the variable name, a syntax slightly different than the one used in C++. C# arrays can be single-dimensional, multidimensional, or jagged. Objects in C# can be treated like arrays through the use of indexers. Indexers allow programmers to easily work with and track many objects of the same type.

by BrainBellupdated