Indexers vs Get.Set methods

I have a class called statTable. It collects and computes a large number of statistics for a variable. One of its members is a list of ints called frequencyCounts. The statTable's constructor defines a set of intervals over the range of the variable being tracked. Every time statTable's Update() method is called with a new value of the variable the frequencyCount corresponding to the interval for that value of the variable is incremented by 1. In addition to the frequency count there are several statistics based upon frequency that the user of a statTable could be interested in accessing. For example, percent, cumulative frequency, cumulative percent. I see three different ways to design my statTable class to provide these statistics to the user.1) Create get Methods for each of the statistics of interest.2) Create an indexer for frequencyCounts and get methods for all statistics created from frequencyCounts.3) Create an enum Statistic, which enumerates all the statistics calculated from frequencyCounts, as well as frequencyCounts itself and an indexer which takes two parameters the Statistic enum and an int i designating the interval.I would like comments both philosophically and practically on the three approaches and any better approach I might have missed.

Answer this question

Indexers vs Get.Set methods

  • jasonboetcher

    I think I understand your answer. In this example, Method 1, create a set of get methods would be the prefered way to go, because the client code never needs write to any variables including frequencyCounts. To help me understand the concept, if frequencyCounts was a variable that could be written to instead of just calculated would one of methods 2) or 3) be preferred. If so which one 2) or 3) Thank you.
  • djshades2004

    You can only have one indexer per class--even if they return different types. If you ever plan on expanding how your class accesses the collection or provides access to other collections you'll have to implement it with something other than an index--leading to an inconsistent interface.

    The benefit of an indexer over a property is you don't have to provide a collection in order for the client code to access an element of that collection. Since you're not providing a collection for the client code to gain access to an element you don't have to deal with the possibility making a duplicate of the list because you don't want to provide write access to the list--which would occur if you had a get property that returned a reference to the list...

    There's a document on MSDN that covers in more detail the differences between indexers and properties called Comparison Between Properties and Indexers (C#) that might be of interest to you.

  • Indexers vs Get.Set methods