Click here to Skip to main content
15,905,508 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Please give me example of indexer in c#.net
Posted
Updated 8-Sep-11 6:04am
v2
Comments
Mehdi Gholam 8-Sep-11 10:10am    
What do you mean by indexer?
vipul ghadge 8-Sep-11 10:14am    
which indexer you need ,C# Or SQL?
GParkings 8-Sep-11 12:04pm    
is this your homework?

1 solution

An indexer is a special type of property that allows a class to appear like an array, i.e. you can index it (hence the name) with square bracket indexing. You use indexers all the time – looking up in a List<T> by index, or a Dictionary by key (or DataRows/Tables/etc).

It's not that common to need an indexer on a custom class, because the collections provided by the framework are generally good enough that when you need something with array like behaviour you can use one (and if you want to forward a list to the class's own indexer you should use the default property, though I'm not sure if that can be done in C#).

The syntax for an indexer is simple:
public int this[int index] {
 get { 
  // retrieve a value from somewhere
  return 42;
 }
 // optional
 set {
  // do something with the value and index
 }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900