Indexer

In this chapter you will learn:

  1. What is indexer
  2. How to create your own indexer
  3. How to create a getter only indexer

What is Indexer

Indexer is for accessing a list of value by using the index. The following code uses the indexer from buildin type string to access each char inside a string.

The indexer can have the following modifiers:

  • static
  • public
  • internal
  • private
  • protected
  • new
  • virtual
  • abstract
  • override
  • sealed
  • unsafe
  • extern

A one-dimensional indexer has this general form:

element-type this[int index] {
    // The get accessor.
    get {/*j a  va2s .c o  m*/
        // return the value specified by index 
    }
    
    // The set accessor.
    set {
        // set the value specified by index 
    }
}

It is possible to overload the [ ] operator for classes that you create with an indexer. An indexer allows an object to be indexed like an array.

using System;//from jav  a  2  s .  com


class Program
{
    static void Main(string[] args)
    {
        string str = "java2s.com";

        Console.WriteLine(str[2]);


    }
}

The output:

Your own indexer

The following code uses the indexer to access each week day.

using System;/*  java2s  . c  o  m*/
class Week
{
    string[] days = new string[] { "Monday", "Tuesday", "Wednesday", 
                    "Thursday", "Friday", "Saturday", "Sunday" };

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


class Program
{
    static void Main(string[] args)
    {
        Week w = new Week();

        Console.WriteLine(w[2]);


    }
}

The output:

Getter only indexer

The Employee class in the following code only has a getter indexer since it only implements the getter part of an indexer.

using System;/* j a va2 s  .c o m*/

public class Employee
{
  private string firstName;
  private string lastName;

  public Employee(string firstName, string lastName)
  {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  public string this[int index]
  {
    get
    {
      switch (index)
      {
        case 0:
          return firstName;
        case 1:
          return lastName;
        default:
          throw new IndexOutOfRangeException();
      }
    }
  }

}

class MainClass
{
  public static void Main()
  {
    Employee myEmployee = new Employee("T", "M");

    Console.WriteLine("myEmployee[0] = " + myEmployee[0]);
    Console.WriteLine("myEmployee[1] = " + myEmployee[1]);

  }

}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Indexing with an String Indexer
  2. Define both int and string indexer for a class
Home » C# Tutorial » Class
Classes and Structs
Encapsulation
Class and Struct Accessibility
Members
Static Members
Class
Class instance variables
Class instance Methods
Class Inheritance
Class constructor
Default constructors
Parameters of constructors
Constructor overloading
Static Constructor
Destructor
Override destructor
new operator
Class field
Static Fields
Read only field
Field default value
const value
Abstract class
Static Class
Partial type
Methods
Method local variable
Method Overloading
Method overloading with ref and out
Type conversion and method overloading
Error in Method overloading
virtual methods
Override methods
Method Parameter
Pass parameters
ref parameters
out parameters
Variable parameter length
Optional parameters
Named parameters
static method
function Return
Recursive methods
Virtual methods and polymorphism
Cast
Shadow inherited members
Seal a member
this keyword
base keyword
base and name hiding
Access Specifiers
private
public
protected
internal
Indexer
String type indexer
Multidimensional indexer
Indexer overloading
Indexer to append
Indexer logic
Properties
Properties getter and setter
Accessibilities of properties
Automatic properties
Read only and write only property
Virtual properties
Abstract Properties
Static Properties
interface
interface implementation
Explicit interface implementation
Interface inheritance
Indexer in an interface
Interface Properties
struct and interface
virtual interface implementation
as operator
is operator
null reference
Nested classes
object class
ToString method
GetHashCode
Object initialization
Extension method
Struct Instances vs. Class Instances