VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/c-sharp-indexers-using-string-as-an-index/

⇱ C# - Indexers Using String as an Index - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C# - Indexers Using String as an Index

Last Updated : 15 Jul, 2025

Prerequisite: Properties in C#

Indexers allow instances of a class or struct to be indexed just like arrays. By using indexers class will behave like a virtual array. The indexed value can be set or retrieved without explicitly specifying a type or instance member. Indexers resemble properties except that their accessors take parameters. Indexers are almost similar to the Properties. The main difference between Indexers and Properties is that the accessors of the Indexers will take parameters.

Indexers using a string as an index:

This method will give you more information, readability. If we want to retrieve information using a string as an index.

Example:

ic["username"] = "user12"; 
ic["password"] = "12345"; 

This will give more readability than the code given below.

ic[0] = "user12"; 
ic[1] = "12345"; 

Syntax:

[access_modifier] [return_type] this [argument_list]
{
 get 
 {
 // retrieval code or code to get the value 
 }
 set 
 {
 // code for setting value to member
 }

In the above syntax:

  • access_modifier: It can be public, private, protected, or internal.
  • return_type: It can be any valid C# type. In this case, it will be of string type.
  • this: It is the keyword which points to the object of the current class.
  • argument_list: This specifies the parameter list of the indexer.
  • get{ } and set { }: These are the accessors.

Example:

Output:

Printing values stored in objects used as arrays
UserName = user12
Password = 12345
Email = user123@gmail.com
Book = CSHARP
Comment
Article Tags:

Explore