jhoyuen
6/4/2016 - 7:23 AM

Indexers enable indexing of a class, struct or an interface to work as an array on these three types

Indexers enable indexing of a class, struct or an interface to work as an array on these three types

Indexers

Work like an array on a class, struct or interface
Declare an indexer on a class or struct with the this keyword
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Characters
/// </summary>
public class Characters
{

    private Character[] charas = { new Character(){ Name = "Jon", Skill="Taichi" }, new Character(){ Name ="Mon", Skill="Phoenix" } };

    public int Length
    {
        get
        {
            return charas.Length;
        }
    }

    public Character this[int index]
    {
        get { return charas[index]; }
        set { charas[index] = value; }
    }

    public Character GetChar(string charaname)
    {
        for (int i = 0; i < charas.Length; i++)
        {
            if (charas[i].Name == charaname)
            {
                return charas[i];
            }
        }

        return null;
    }

    public Character this[string charaname]
    {
        get { return GetChar(charaname); }
    }
}

public class Character
{
    public string Name { get; set; }
    public string Skill { get; set; }
}

Using the indexer from the above example

Code below is in the page load event of the code-behind of a default.aspx page

Characters chars = new Characters();

chars[0] = chars["Mon"];

chars[1] = new Character();
chars[1].Name = "Ken";
chars[1].Skill = "sandstorm";

for (int i =0; i < chars.Length; i++)
{
    Response.Write("char name: " + chars[i].Name + " and char skill: " + chars[i].Skill + "<br />");
}