Indexers

Indexers are a new concept in C#. Indexers enable a class object to function as an array. Implementing indexers is similar to implementing properties using the get and set functions. The only different is that when you call an indexer, you pass an indexing parameter. Accessing an indexer is similar to accessing an array. Indexers are nameless, so the this keyword declares indexers.

I just said that after defining indexers, a class object could be treated as an array. What does that mean? To explain, I‘ll show you an example using the class called my class. The way you treat an instance of myClass now is like this:


myClass cls = new myClass();
cls.MaleGender = true;

After defining an indexer in myClass, you could treat an instance of it as if it were an array:

myClass cls = new myClass();
cls[0].MaleGender = true;
cls[1].MaleGender = true;

You define indexer by using the this keyword as if were an array property of type object.

public object this[int index]
{
get
{
if (! ValidIndex(index))
throw new Exception("Index out of range.");
else
return MaleGender(index).Value;
}
set
{
if (!ValidIndex(index) )
throw new Exception("Index out of range.");
else
MaleGender(index).Value = value;
}
}


Comments

Author: Phagu Mahato18 Feb 2014 Member Level: Gold   Points : 6

An indexer provides array-like syntax. It allows a type to be accessed the same way as an array.Example code as menion below
this [Parameter]

{

get

{

// Get codes goes here

}

set

{

// Set codes goes here

}

}



using System;

class Layout
{
string[] _values = new string[100];
public string this[int number]
{
get
{

if (number >= 0 && number < _values.Length)
{

return _values[number];
}

return "Error";
}
set
{

if (number >= 0 && number < _values.Length)
{

_values[number] = value;
}
}
}
}

class Program
{
static void Main()
{
MyMyLayout MyMyLayout = new MyMyLayout();
MyMyLayout[1] = "Frank Gehry";
MyMyLayout[3] = "I. M. Pei";


string value1 = MyMyLayout[1];
string value2 = MyLayout[3];
string value3 = MyLayout[10];



Console.WriteLine(value1);
Console.WriteLine(value2);
Console.WriteLine(value3);

}
}



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: