Professional Documents
Culture Documents
C# 30
C# 3.0
Chapter 10 Indexers
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 2
C# 30
Indexers Motivation
To enable a container class to pro
provide
ide
intuitive access to its elements, C# offers
an indexer
Indexers allow you to index a class or a struct
instance in the same way as an array
For
F example:
l keeping
k
i boolean
b l
i f
information
ti in
i compactt
bit storage, while exposing it, through an indexer, as
an array of bool elements
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 3
C# 30
An Indexer Example
Assume the following EmployeeManager
class that stores employees
p y
classEmployeeManager
{
privateint _numEmployees =0;
privateEmployee[]_employees;
publicint NumEmployees
publicEmployeeManager(int maxEmployees)
maxEmployees)
publicbool Add(Employeee)
publicvoidSortByName()
publicvoidSortBySalary()
publicvoidPrint()
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 4
C# 30
An Indexer Example
publicEmployeethis[int index]
{
get
{
if(index<0||index>=_numEmployees)
returnnull;
else
return_employees[index];
}
set
{
if(!(index<0||index>=_numEmployees))
_employees[index]=value;
}
}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 5
C# 30
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 6
C# 30
[attributes]
[modifiers]
type
Th type
The
t
handled
h dl d b
by th
the iindexer
d
((get
t and
d set)
t)
[indexparameterlist]
publicEmployeethis[int index]
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 7
C# 30
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 8
C# 30
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
Indexers 9
C# 30
Chapter 10 Exercise 1
Indexers 10
C# 30
Summary
Following are some of the indexers special
characteristics:
They have (in C#) an hard coded name: Item
They have an optional (greater than zero) number of
parameters
They are accessed through the array element access
[]
[]syntax
t
They are identified by their signature
Properties are defined by their name
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel