Showing posts with label Property vs Indexer. Show all posts
Showing posts with label Property vs Indexer. Show all posts

Saturday, June 2, 2012

Indexer in C#

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.
In the following example, a generic class is defined and provided with simple get and set accessor methods as a means of assigning and retrieving values. The Program class creates an instance of this class for storing strings.



class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];
    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.
    // (See line 2 of code in Main below.)       
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}
// This class shows how client code uses the indexer.
class Program
{
    static void Main(string[] args)
    {
        // Declare an instance of the SampleCollection type.
        SampleCollection<string> stringCollection = new SampleCollection<string>();
        // Use [] notation on the type.
        stringCollection[0] = "My Name is Psingh";
        System.Console.WriteLine(stringCollection[0]);
    }
}

Output:
"My Name is Psingh"


 

Comparison Between Properties and Indexers

Indexers are similar to properties. Except for the differences shown in the following table, all of the rules defined for property accessors apply to indexer accessors as well.

PropertyIndexer
Identified by its name.Identified by its signature.
Accessed through a simple name or a member access.Accessed through an element access.
Can be a static or an instance member.Must be an instance member.
A get accessor of a property has no parameters.A get accessor of an indexer has the same formal parameter list as the indexer.
A set accessor of a property contains the implicit value parameter.A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.