C# – Indexers Using String as an Index
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:
C#
using System;
class IndexerPOC
{
private string [] val = new string [4];
private string [] indices={ "username" , "password" , "email" , "Book" };
public string this [ string index]
{
get
{
return val[Array.IndexOf(indices,index)];
}
set
{
val[ Array.IndexOf(indices,index)] = value;
}
}
}
class Program {
public static void Main() {
IndexerPOC ic = new IndexerPOC();
ic[ "username" ] = "user12" ;
ic[ "password" ] = "12345" ;
ic[ "email" ] = "user123@gmail.com" ;
ic[ "Book" ]= "CSHARP" ;
Console.Write( "Printing values stored in objects used as arrays\n" );
Console.WriteLine( "UserName = {0}" , ic[ "username" ]);
Console.WriteLine( "Password = {0}" , ic[ "password" ]);
Console.WriteLine( "Email = {0}" , ic[ "email" ]);
Console.WriteLine( "Book = {0}" , ic[ "Book" ]);
}
}
|
Output:
Printing values stored in objects used as arrays
UserName = user12
Password = 12345
Email = user123@gmail.com
Book = CSHARP
Last Updated :
08 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...