Syntax: Element Type Index
Syntax: Element Type Index
When you
define an indexer for a class, this class behaves similar to a virtual array.
You can then access the instance of this class using the array access
operator ([ ]).
Syntax
A one dimensional indexer has the following syntax:
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a
property. similar to the properties, you use get and set accessors for
defining an indexer. However, properties return or set a specific data
member, whereas indexers returns or sets a particular value from the
object instance. In other words, it breaks the instance data into smaller
parts and indexes each part, gets or sets each part.
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following
result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Overloaded Indexers
Indexers can be overloaded. Indexers can also be declared with multiple
parameters and each parameter may be a different type. It is not
necessary that the indexes have to be integers. C# allows indexes to be
of other types, for example, a string.
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
public int this[string name]
{
get
{
int index = 0;
while(index < size)
{
if (namelist[index] == name)
{
return index;
}
index++;
}
return index;
}
When the above code is compiled and executed, it produces the following
result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Property Indexer
A get accessor of a property has no A get accessor of an indexer has the same formal
parameters. parameter list as the indexer.
Property Indexer
A set accessor of a property contains A set accessor of an indexer has the same formal
the implicit value parameter. parameter list as the indexer, and also to
the value parameter.
Supports shortened syntax with Auto- Does not support shortened syntax.
Implemented Properties.