Indexer in C#

Introduction

Indexer is new concept in C#. C# introduced new concept about array i.e. indexer. Indexer is used for create the array of object. Indexer is also known as virtual array and smart array. Indexer modifier can be public, private, internal or protected. It allows you to better manage complex data structures, hiding some complexity from other programmers.

A drawback of indexers in C# is that they can only be given the name of the class in which they're defined - hence the 'this' keyword in the definition. You can't give them some arbitrary name like you can for a non-indexed property.

There are two type of indexer in c#,which are as follows.

1. Single Dimensional Indexer
2. Multidimensional indexer

Single Dimensional Indexer

A single dimensional indexer denotes only row data.

Example :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace indexer
{
    class year
    {
        string[] months = new string[] { "Jan""Feb""March""April""May""Jun""July""Aug""Sep""Nov""December" };
 
        public string this[int i]
        {
            get
            {
                return months[i];
            }
            set
            {
                months[i] = value;
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            year y = new year(); 
            Console.WriteLine(y[2]);
            Console.ReadLine();
        }
    }
}

Output 

image2.png

Multidimensional Indexer

A multidimensional indexer denotes the data in the form of rows and columns.

Example :


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
namespace indexer
{
    class TwoDimension
    {
        int[,] array ={
                         {0,1,2},
                         {3,4,5},
                         {6,7,8}
                      };
    public int this[int i, int j]
        {
            get
            {
                return array[i, j];
            }
        }
  }
    class Program
    {
        static void Main(string[] args)
        {
            TwoDimension t = new TwoDimension();
            Console.WriteLine(t[2, 1]);
            Console.ReadLine();
        }
    }
}

Output

image1.png

Summary

So indexer is the new concept in C# which acts as a smart array or virtual array. When we want to create the object of array then we use indexer in C#.

Ebook Download
View all
Learn
View all