Home > DeveloperSection > Blogs > Indexer in C#

Indexer in C#


.NET C#  Index 
Ratings:
0 Comment(s)
 606  View(s)
Rate this:

Indexer in C#

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

 ·         An indexer allows programmer to create 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)

        {

            Program obj = 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

 


Don't want to miss updates? Please click the below button!

Follow MindStick