In this blog, I’m explaining about Indexer in C#

  •  An indexer allows the programmer to create a class that can act like virtual arrays.
  • We can access instances of those classes using the [] array access operator.
  • An indexer can have private, public, protected or internal modifier & the return type can be any valid C# types.   
  • An indexer in c# must have at least one parameter.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace IndexersExample
{
  
    class Program
    {
        static public string[] namelist = new string[0];
        public string this[int index]
        {
            get
            {
                string temp;
                if (index >= 0 && index < namelist.Length)
                    temp = namelist[index];
                else
                    temp = "";
                return (temp);
            }
            set
            {
                if (index >= 0&& index < namelist.Length) namelist[index] = value;
            }
        }
static void Main(string[]args)
        {
            Programobj = new Program();
            int size;
            Console.WriteLine("Enter Array size");
            size=Convert.ToInt32(Console.ReadLine());
            namelist = new string[size];
            for (int i = 0; i <namelist.Length; i++)
            {
                Console.WriteLine("Enter string");
                obj[i] = Console.ReadLine();
            }
            Console.WriteLine("----------Output---------");
            for (int i = 0; i <= namelist.Length; i++)
            {
                Console.WriteLine(obj[i]);
            }
            Console.ReadKey();
        }
    }
}
 
Output:
Enter Array size
3
Enter string
Abc
Enter string
Xyz
Enter string
Opq
----------Output-------------
A
Xyz
Opq

 

  Modified On Feb-22-2018 04:10:28 AM

Leave Comment