Indexers in C# .NET
Indexer allows classes to be used in more intuitive manner. C# introduces a new concept known as Indexers which are used for treating an object as an array. The indexers are usually known as smart arrays in C#. They are not essential part of object-oriented programming.
An indexer, also called an indexed property, is a class property that allows you to access a member variable of a class using the features of an array.
Defining an indexer allows you to create classes that act like virtual arrays. Instances of that class can be accessed using the [] array access operator.
Creating an Indexer
<modifier> <return type> this [argument list]
{
get
{
// your get block code
}
set
{
// your set block code
}
}
In the above code:
<modifier>
can be private, public, protected or internal.
<return type>
can be any valid C# types.
this
this is a special keyword in C# to indicate the object of the current class.
[argument list]
The formal-argument-list specifies the parameters of the indexer.
Important points to remember on indexers:
-
Indexers are always created with this keyword.
-
Parameterized property are called indexer.
-
Indexers are implemented through get and set accessors for the [ ] operator.
-
ref and out parameter modifiers are not permitted in indexer.
-
The formal parameter list of an indexer corresponds to that of a method and at least one parameter should be specified.
-
Indexer is an instance member so can't be static but property can be static.
-
Indexers are used on group of elements.
-
Indexer is identified by its signature where as a property is identified it's name.
-
Indexers are accessed using indexes where as properties are accessed by names.
-
Indexer can be overloaded.
Indexer are defined in pretty much same way as properties, with get and set functions. The main difference is that the name of the indexer is the keyword this.
Following program demonstrate how to use indexer.
using System;
namespace Indexer_example1
{
class Program
{
class IndexerClass
{
private string[] names = new string[10];
public string this[int i]
{
get
{
return names[i];
}
set
{
names[i] = value;
}
}
}
static void Main(string[] args)
{
IndexerClass Team = new IndexerClass();
Team[0] = "Rocky";
Team[1] = "Teena";
Team[2] = "Ana";
Team[3] = "Victoria";
Team[4] = "Yani";
Team[5] = "Mary";
Team[6] = "Gomes";
Team[7] = "Arnold";
Team[8] = "Mike";
Team[9] = "Peter";
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Team[i]);
}
Console.ReadKey();
}
}
}
Difference between Indexers and Properties
Indexers are commonly used for classes, which represents some data structure, an array, list, map and so on.
Conclusion
Hope the article would have helped you in understanding indexer. Your feedback and constructive contributions are welcome. Please feel free to contact me for feedback or comments you may have about this article.