- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are indexers in C#?
An indexer allows an object to be indexed such as an array.
Let us see the syntax −
element-type this[int index] { // The get accessor. get { // return the value specified by index } // The set accessor. set { // set the value specified by index } }
The following is an example showing how to implement indexers in C# −
Example
using System; namespace Demo { class Program { private string[] namelist = new string[size]; static public int size = 10; public Program() { for (int i = 0; i < size; i++) namelist[i] = "N. A."; } public string this[int index] { get { string tmp; if( index >= 0 && index <= size-1 ) { tmp = namelist[index]; } else { tmp = ""; } return ( tmp ); } set { if( index >= 0 && index <= size-1 ) { namelist[index] = value; } } } static void Main(string[] args) { Program names = new Program(); names[0] = "Tom"; names[1] = "Jacob"; names[2] = "Jack"; names[3] = "Amy"; names[4] = "Katy"; names[5] = "Taylor"; names[6] = "Brad"; names[7] = "Scarlett"; names[8] = "James"; for ( int i = 0; i < Program.size; i++ ) { Console.WriteLine(names[i]); } Console.ReadKey(); } } }
Output
Tom Jacob Jack Amy Katy Taylor Brad Scarlett James N. A.
Advertisements