

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 overloaded indexers in C#?
An indexer in C# allows an object to be indexed such as an array. When an indexer for a class is defined, this class behaves similar to a virtual array. You can then access the instance of this class using the array access operator ([ ]).
Indexers can be overloaded. Indexers can also be declared with multiple parameters and each parameter may be a different type.
The following is an example of overloaded indexers in C# −
Example
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."; } } 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; } } } public int this[string name] { get { int index = 0; while(index < size) { if (namelist[index] == name) { return index; } index++; } return index; } } static void Main(string[] args) { IndexedNames names = new IndexedNames(); names[0] = "John"; names[1] = "Joe"; names[2] = "Graham"; names[3] = "William"; names[4] = "Jack"; names[5] = "Tom"; names[6] = "Tim"; //using the first indexer with int parameter for (int i = 0; i < IndexedNames.size; i++) { Console.WriteLine(names[i]); } //using the second indexer with the string parameter Console.WriteLine(names["Nuha"]); Console.ReadKey(); } } }
Output
John Joe Graham William Jack Tom Tim N. A. N. A. N. A. 10
- Related Questions & Answers
- What are indexers in C#?
- What are the different ways for a method to be overloaded in C#?
- How to use indexers in C# 8.0?
- Overloaded method and ambiguity in C#
- Can main() be overloaded in C++?
- Operators that cannot be overloaded in C++
- Functions that cannot be overloaded in C++
- Pass long parameter to an overloaded method in Java
- Functions that can’t be overloaded in C++
- Hiding of all overloaded methods in base class in C++
- How to implement Python __lt__ __gt__ custom (overloaded) operators?
- Use overloaded methods to print array of different types in Java
- If I change the return type, will the method gets overloaded in java?
- What are Microwaves? What are they used for?
- What are carbohydrates? What are their advantages and disadvantages?
Advertisements