Home » .Net

Indexer overloading in C#

In this article, we are going to learn about Indexer overloading in C#, how to implement program to demonstrate indexer overloading in C#.
Submitted by IncludeHelp, on August 11, 2018

Prerequisite: Indexers in C#

We can overload indexers in C#. We can declare indexers with multiple arguments and every argument have different data-types. It is not compulsory that indexes must be integer type. Indexes can be different types 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] = "Duggu";
            names[1] = "Shaurya";
            names[2] = "Akshit";
            names[3] = "Shivika";
            names[4] = "Veer";

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

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

        }
    }
}

Output

    Duggu
    Shaurya
    Akshit
    Shivika
    Veer
    N/A
    N/A
    N/A
    N/A
    N/A
    Index : 1


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.