Indexer
In this chapter you will learn:
What is Indexer
Indexer is for accessing a list of value by using the index. The following code uses the indexer from buildin type string to access each char inside a string.
The indexer can have the following modifiers:
- static
- public
- internal
- private
- protected
- new
- virtual
- abstract
- override
- sealed
- unsafe
- extern
A one-dimensional indexer has this general form:
element-type this[int index] {
// The get accessor.
get {/*j a va2s .c o m*/
// return the value specified by index
}
// The set accessor.
set {
// set the value specified by index
}
}
It is possible to overload the [ ] operator for classes that you create with an indexer. An indexer allows an object to be indexed like an array.
using System;//from jav a 2 s . com
class Program
{
static void Main(string[] args)
{
string str = "java2s.com";
Console.WriteLine(str[2]);
}
}
The output:
Your own indexer
The following code uses the indexer to access each week day.
using System;/* java2s . c o m*/
class Week
{
string[] days = new string[] { "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday" };
public string this[int i]
{
get
{
return days[i];
}
set
{
days[i] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Week w = new Week();
Console.WriteLine(w[2]);
}
}
The output:
Getter only indexer
The Employee
class in the following code only has a getter indexer
since it only implements the getter part of an indexer.
using System;/* j a va2 s .c o m*/
public class Employee
{
private string firstName;
private string lastName;
public Employee(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public string this[int index]
{
get
{
switch (index)
{
case 0:
return firstName;
case 1:
return lastName;
default:
throw new IndexOutOfRangeException();
}
}
}
}
class MainClass
{
public static void Main()
{
Employee myEmployee = new Employee("T", "M");
Console.WriteLine("myEmployee[0] = " + myEmployee[0]);
Console.WriteLine("myEmployee[1] = " + myEmployee[1]);
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Class