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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.