Saturday, March 20, 2010

Indexer class in C#

While taking interviews for Microsoft.NET i often ask about indexer classes in C#.NET and i found that most of people are unable to give answer that how we can create a indexer class in C#.NET. We know the array in C#.NET and each element in array can be accessed by index same way for indexer class a object was class can be accessed by index. Its very easy to create a indexer class in C#. First lets looks some points related to indexer class in C#.

  • Indexer class object can be accessed by index only.
  • We can use same mechanism to access object of indexer class as we are doing it for array.
  • You can can specify any valid C# type as return type of indexer classes.
  • You must have to create a property with parameter using this keyword for indexer class.
  • You can also implement multi parameter indexer also.

Let’s create simple indexer class with single parameter and for string type.

 public class MyIndexer
private string[] MyIndexerData;
private int SizeOfIndexer;

//declaring cursor to assing size of indexer
public MyIndexer(int sizeOfIndex)
this.SizeOfIndexer = sizeOfIndex;
MyIndexerData = new string[SizeOfIndexer];

public string this[int Position]
return MyIndexerData[Position];
MyIndexerData[Position] = value;
Now we done with indexer class and lets create object of that indexer class and will see output of our console application also. Following is the code for that.
namespace ConsoleApplication1
class Program
static void Main(string[] args)
int indexSize=5;
MyIndexer objMyIndexer = new MyIndexer(indexSize);
for (int i = 0; i < indexSize; i++)
objMyIndexer[i] = i.ToString();
Console.WriteLine("Indexer Object Value-[{0}]: {1}",
i, objMyIndexer[i]);
and Here is the output for the indexer class console application.

Indexer Class Example in C#,Indexer Class,C#

Technorati Tags: ,,
Shout it
kick it on

1 comment:

  1. I think the problem you are having finding a person who can create an "indexer class" is due to your rather vague definition of what an "indexer class" is.

    If you were to refer to it instead as "a class with an indexer property (and no other API)", you might have more success.

    Upon reading the term "indexer class", I was expecting an object with some special properties that made it especially useful when passed as the index to some other class with had an indexer property. i.e.:

    var i = new Indexer();
    var C = new SomeCollection();

    var v = C[i]; // special magic happens here!


Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews