Indexer in C# - ProgramIdea

Indexer in C#


Before going to learn about indexer in C#, first see where we are using indexers every day. If you ask to fresher about indexer, they say no, I never used indexer. But actually they are using every day in programming. How? Let’s see. When you use session, then you are using square bracket for saving and retrieving session object.

demo

You are using integer value inside square bracket means you calling session object by index. Exactly at this point you are using indexer because indexer allow you to indexed class just like arrays. Benefits of indexer is to get a particular object reference from a collection instead of searching one by one all items in collection.

You can use indexer where you use class collection and due to indexer you can easily get the reference of object from the collection.

  • Indexer allow instances of a class or struc to be indexed just like arrays.
  • A get accessor return a value ane a set accessor assign a value.
  • The this keyword is used to define the indexer.
  • They accept an index value in place of the standard property value parameter.
  • They are identified through the use of the keyword this.
  • Indexed properties property can be created in classes or structs.
  • Only one indexed property can exists in a single class or struct.
  • They can contain get and set methods just like other properties.
  • Indexer can be overloaded.
  • Properties are used to access single values in classes, whereas an indexer are used to encapsulate a set of values of class.

Indexer by intenger

public partial class CSharp_Indexer  : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Students student = new Students();
        student[0] = "Hello";
        student[1] = "Asp";
        student[2] = "Helps"; 

        Response.Write(student[0]);
        Response.Write(student[1]);
        Response.Write(student[2]); 

        // Output
        // Hello
        // Asp
        // Helps
    }
}
public class Students
{
    private string[] str = new string[10]; 

    public string this[int i]
    {
        get
        {
            return str[i];
        }
        set
        {
            str[i] = value;
        }
    }
}