Home > Tutorial for Beginners > Tutorial – Indexers in C#

Tutorial – Indexers in C#

Applicable: C# 3.5

Definitions: Indexers was introduced in C# 2.0. Indexers are very similar to array, however, they are very close to the way when used in vb (setters and getters) to access the values. They are used to define the property and provide access to a value of an array outside the class. In array you can access any item or element by using index number which is an integer value. In indexer you can access elements with the name of key rather than value. Like array Indexers can be overloaded. Indexer must have one parameter.

Syntax: <Modifier> type this[type parameter]: where

modifier can be private/public /protected/internal

type: Any Valid type In C#(int, string etc)

this: represent the object of the current class

Parameter: formal – argument list, at least one parameter has to be there, to avoid the compiler error.


Declaration of Indexer in class

public class IndexerSample


    string[] myArray;

    public IndexerSample(int arrSize)


        myArray = new string[arrSize];

        //code to assgin values goes here



    public int this[int Index_no]


        get {return Index_no;}

        set {Index_no = value;}




Now create the object of IndexerSample Class in your page where you want to user this indexer, I am creating in page_Load event as

protected void Page_Load(object sender, EventArgs e)


        //in your page(I am assuming Web page)


        IndexerSample objISampel = new IndexerSample(4);


        // setting the new value

        objISampel[0] = 8;

        objISampel[1] = 13;

        objISampel[2] = 8;

        objISampel[3] = 27;


        // get the new value from array


        for (int i = 0; i <= 3; i++)


            Response.Write(objISampel[i] + “</br>”);





Tutorial - Indexers in C#, Code output

Categories: Tutorial for Beginners Tags:

Post Comments Below

  1. No comments yet.
  1. No trackbacks yet.