Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Indexers
3.
Creating Indexers
4.
Example Code
5.
Overloaded Indexers
6.
Points to Remember
7.
FAQs
7.1.
How do get and set differ from eachother?
7.2.
What does the this keyword do?
7.3.
What does the value keyword do?
7.4.
Is it necessary to index the indexers using integer value?
7.5.
How many formal parameters can an Indexer have?
8.
Conclusion
Last Updated: Mar 27, 2024

C# Indexers

Author Toohina Barua
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

The programming language C# (pronounced "See Sharp") is modern, object-oriented, and type-safe. C# allows developers to create a wide range of secure and reliable.NET applications.
An indexer allows an object, such as an array, to be indexed. When you give a class an indexer, it acts like a virtual array.
In this article, we will learn about Indexers in C# by looking at some coding examples. So let us dive in!

Indexers

C# indexers are usually known as smart arrays. A C# indexer is a class property that allows you to use the features of an array to access a member variable of a class or struct. This keyword is used to create indexers in C#. In C#, indexers can be used on both classes and structs. 
By defining an indexer, you can create a class that can have its items accessed as an array. The [] array access operator can be used to access instances of that class.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Creating Indexers

The following code demonstrates how to create Indexers:

<modifier> <return type> this [argument list]  
{  
get  
{  
// your get block code  
}  
set  
{  
// your set block code  
}  
}  


In the code above:
<modifier> can be private, public, protected or internal.
<return type> can be any valid C# types.
"this" is a special keyword in C# to indicate the object of the current class.
The formal-argument-list, that is, [argument list], specifies the parameters of the indexer.

Example Code

The code given below shows how to use Indexers:

using System;  
namespace Indexer_example 
{  
    class Program  
    {  
        class IndexerClass  
        {  
            private string[] str= new string[10];  
            public string this[int i]  
            {  
                get  
                {  
                    return str[i];  
                }  
                set  
                {  
                   str[i] = value;  
                }  
            }  
        }  
        static void Main(string[] args)  
        {  
            IndexerClass Sentence = new IndexerClass();  
            Sentence[0] = "Coding";  
            Sentence[1] = "Ninjas";  
            Sentence[2] = "is";  
            Sentence[3] = "an";  
            Sentence[4] = "Awesome";  
            Sentence[5] = "Platform";  
            Sentence[6] = "for";  
            Sentence[7] = "learning";  
            Sentence[8] = "and";  
            Sentence[9] = "coding";  
            for (int i = 0; i < 10; i++)  
            {  
                Console.WriteLine(Sentence[i]);  
            }  
            Console.ReadKey();  
        }  
    }  
}

Overloaded Indexers

Overloaded indexers are possible. Indexers can also have multiple parameters, each of which can be of a different type. It is not required that the indexes are integers. In C#, indexes can be of any type, including strings.

Overloaded indexers are demonstrated in the following example:

using System;

namespace IndexerApplication {
   class IndexedWords {
      private string[] wordlist = new string[size];
      static public int size = 10;
      
      public IndexedWords() {
         for (int i = 0; i < size; i++) {
            wordlist[i] = "N. A.";
         }
      }
      public string this[int index] {
         get {
            string tmp;
            
            if( index >= 0 && index <= size-1 ) {
               tmp = wordlist[index];
            } else {
               tmp = "";
            }
            
            return ( tmp );
         }
         set {
            if( index >= 0 && index <= size-1 ) {
               wordlist[index] = value;
            }
         }
      }
      
      public int this[string word] {
         get {
            int index = 0;
            
            while(index < size) {
               if (wordlist[index] == word) {
                return index;
               }
               index++;
            }
            return index;
         }
      }

      static void Main(string[] args) {
         IndexedNames words = new IndexedWords();
         words[0] = "Coding";
         words[1] = "Ninjas";
         words[2] = "is";
         words[3] = "an";
         words[4] = "awesome";
         words[5] = "coding";
         words[6] = "platform";
         
         //using the first indexer with int parameter
         for (int i = 0; i < IndexedWords.size; i++) {
            Console.WriteLine(words[i]);
         }
         
         //using the second indexer with the string parameter
         Console.WriteLine(words["is"]);
         Console.ReadKey();
      }
   }
}


When the above code is compiled and run, the following is the result:

Coding
Ninjas
is
an
awesome
coding
platform
N. A.
N. A.
N. A.
2

Points to Remember

  • This keyword is always used when creating indexers.
  • Indexers are parameterized properties.
  • Get and set accessors for the [] operator are used to implement indexers.
  • Indexer does not allow ref and out parameter modifiers.
  • An indexer's formal parameter list is similar to that of a method, and at least one parameter must be specified.
  • Because indexer is an instance member, it cannot be static, but property can.
  • On groups of elements, indexers are used.
  • A property is identified by its name, whereas an indexer is identified by its signature.
  • Indexes are used to access indexers, while names are used to access properties.
  • The indexer can become overburdened.

Must Read IEnumerable vs IQueryablesingleton design pattern in c#

FAQs

How do get and set differ from eachother?

Get and set accessors for the [] operator are used to implement indexers. An indexer's get accessor has the same formal parameter list as the indexer itself.In addition to the value parameter, an indexer's set accessor has the same formal parameter list as the indexer. A get accessor returns a value. A set accessor assigns a value.

What does the this keyword do?

The this keyword is used to define the indexer. This keyword is not required for properties. Indexers are parameterized properties. This keyword is used to create indexers

What does the value keyword do?

The value keyword is used to define the value being assigned by the set accessor. The contextual keyword value is used in the set accessor in property and indexer declarations. It is similar to an input parameter of a method. The word value references the value that client code is attempting to assign to the property or indexer.

Is it necessary to index the indexers using integer value?

It is not necessary to index the indexers using integer values. Indexers do not have to be indexed by an integer value; how you define the specific look-up mechanism is entirely up to you.

How many formal parameters can an Indexer have?

Indexers can have more than one formal parameter. When accessing a two-dimensional array, for example, indexers can have multiple formal parameters.

Conclusion

In this article, we discussed the theoretical and practical implementation of Indexers in C#. 
We hope that this blog has helped you enhance your knowledge regarding the Indexers in C# and if you would like to learn more about MethodsType Conversionsclasses and objects in C#, check out our articles on Coding Ninjas Studio. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Tuples in C#
Next article
Difference between IEnumerable vs IQueryable
Live masterclass