C#

Learning Indexers in C#

Programmingempire

C# language has an important feature called Indexer which allows us to represent objects as arrays. In this post on Learning Indexers in C#, I will discuss Indexers and also demonstrate their usage with the help of a few examples.

Basically, an indexer is a syntactical convenience that enables us to work with arrays that a class definition contains using only the object of that class. In other words, in the client program, we don’t need to declare or create arrays, we just create an object of that class. Specifically, the indexers simplify the syntax for those objects which contain collections as their data members.

Syntax of Creating Indexers

access-specifier return-type this[argument-list]
{
      get
      {
          // statements
      }
      set
      {
          // statements
      }
}

Important Points about Indexers

  1. We create indexers using this keyword.
  2. A class can define more than one indexers, all having different argument list.
  3. Depending upon, the number of arguments present in the argument-list, indexers are one-dimensional or multi-dimensional.
  4. Indexers have the get and set accessors.
  5. At least one of the get or set accessors should be present in the indexer, both of them can’t be missing.

Learning Indexers in C# with Examples

Example 1: Display IDs of 10 Students using Indexer

In this example, the class Student contains an integer array. Also, this class has an indexer that takes an integer parameter and returns an integer value. Further, the get accessor returns the ith element of the array and the set accessor sets the value of the ith element.

In the main() method, the indexer assigns the value to array elements using the object name and subscript. For instance, ob[i]=i+1; This statement calls the set accessor of the indexer. Further, The next for loop displays the value of array elements using Console.WriteLine() statement, which calls the get accessor.

using System;
namespace IndexerDemo1
{
    class Program
    {
        static void Main(string[] args)
        {
            StudentIDs ob = new StudentIDs();
            //Creating IDs of 10 students
            for(int i=0;i<10;i++)
            {
                ob[i] = i + 1;
            }
            //Display IDs of 10 students
            Console.WriteLine("Displaying IDs: ");
            for(int i=0;i<10;i++)
            {
                Console.Write(ob[i] + " ");
            }
        }
    }
    class StudentIDs
    {
        int[] ids = new int[10];
        public int this[int i]
        {
            get
            {
                return ids[i];
            }
            set
            {
                ids[i] = value;
            }
        }
    }
}

Output:

Learning Indexers in C#
Learning Indexers in C#

Example 2: Display the elementsn of a string array using indexer.

This example demonstrates an indexer that takes an integer as a parameter and returns a string. As shown in the code, the class Book has a String array with name titles.

Also, the class contains an indexer that has only a get accessor which returns the ith element of the String array. Further, the get accessor also checks whether the index sent as a parameter is valid or not. If it is not valid, it returns null.

using System;
namespace IndexersDemo2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Displaying Book Titles using Indexer: ");
            Book ob = new Book();
            int i = 0;
            while(true)
            {
                String s = ob[i];
                if (s == null)
                {
                    Console.WriteLine("Exiting...");
                    break;
                }
                else
                {
                    Console.WriteLine(s);
                    i++;
                }
            }
        }
    }
    class Book
    {
        string[] titles = new string[] { "C#", "C", "C++", "PHP", "Java" };
        public string this[int i]
        {
            get
            {
                if (i < titles.Length)
                    return titles[i];
                else
                    return null;
            }
        }
    }
}

Output:

A One-Dimensional Indexer Returning Strings
A One-Dimensional Indexer Returning Strings

Overloading of Indexers

Example 3: Demonstrate overloading of indexers.

In this example, the class called MyClass contains three overloaded indexers. Firstly, the indexer with integer parameter converts the ith element of the integer array which this class contains into a string by adding the number 64. Therefore, this indexer generates the first ten capital letters.

Secondly, the indexer with the String parameter contains only a get accessor, that returns the length of this string. In fact, the use of only get accessor makes this indexer read-only.

Finally, the third indexer, which is a two-dimensional indexer, takes a string parameter and an integer parameter. This indexer also has only get accessor, that encrypts the given string by translating each character of the string to a new character by adding the specified integer parameter value to the ASCII code of that character. Therefore, this particular indexer encrypts the specified string.

using System;
namespace IndexerDemo4
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass ob = new MyClass();
            Console.WriteLine("Converting integers to strings using Indexer: ");
            for(int i=0;i<10;i++)
            {
                Console.WriteLine(ob[i]);
            }

            Console.WriteLine("Using Indexer to get length of a string: ");
            Console.WriteLine("Enter a string:");
            String str = Console.ReadLine();
            Console.WriteLine(ob[str]);

            Random r = new Random();
            int x = r.Next(1, 10);
            Console.WriteLine("Encrypted above String using indexer: ");
            Console.WriteLine(ob[str, x]);

        }
    }
    class MyClass
    {
        int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        public String this[int i]
        {
            get
            {
                return ((char)(arr[i] + 64)).ToString();
            }
        }
        public int this[String s]
        {
            get
            {
                return s.Length;
            }
        }
        public String this[String s, int a]
        {
            get
            {
                string s1 = "";
                char[] ch = new char[s.Length];
                ch = s.ToCharArray();
                for(int i=0;i<ch.Length; i++)
                {
                    ch[i] = (char)((int)ch[i] + a);
                }
                for(int i=0;i<ch.Length;i++)
                {
                    s1 = s1 + ch[i];
                }
                
                return s1;
            }
        }
    }
}

Output:

Overloading Indexers
Overloading Indexers

Summary

In short, an indexer simplifies the accessing and manipulation pf collections which a class contains. As shown above, we can have multiple indexers in one class. However, all these indexers have different numbers of parameters to allow overloading.

programmingempire

You may also like...