Indexer overloading in C#

In this article, we will find out about Indexer over-burdening in C#, how to execute a program to show indexer over-burdening in C#.

We can over-burden indexers in C#. We can proclaim indexers with various contentions and each contention have various information types. It isn’t obligatory that files must be an integer type. Records can be various sorts like string.

Example:

using System;
using System.Collections;
namespace ConsoleApplication1
{
    
    class Names
    {
        static public int len=10;
        private string []names = new string[len]    ;


        public Names()
        {
            for (int loop = 0; loop < len; loop++)
                names[loop] = "N/A";
        }
        public string this[int ind]
        {
            get
            {
                string str;
                if (ind >= 0 && ind <= len - 1)
                    str = names[ind];
                else
                    str = "...";
                return str;
            }

            set
            {
                if (ind >= 0 && ind <= len - 1)
                    names[ind]=value;
            }
        }

        public int this[string name]
        {
            get
            {
                int ind=0;

                while (ind < len)
                {
                    if (names[ind] == name)
                        return ind;
                    ind++;
                }
                return ind;
            }
        }
    }

    class Program
    {
        static void Main()
        {
            Names names = new Names();

            names[0] = "Durgesh";
            names[1] = "Kishan";
            names[2] = "Aakash";
            names[3] = "Vivek";
            names[4] = "Vibhav";

            //first indexer
            for (int loop = 0; loop < Names.len; loop++)
            {
                Console.WriteLine(names[loop]);
            }

            //second indexer
            Console.WriteLine("Index : "+names["Shaurya"]);

        }
    }
}

Output

    Durgesh
    Kishan
    Aakash
    Vivek
    Vibhav
    N/A
    N/A
    N/A
    N/A
    N/A
    Index : 1

Leave a Comment

error: Alert: Content is protected!!