Indexer: The indexer allows instances of classes or structures to be indexed in the same way as arrays. The indexer is similar to an attribute, but its accessors use parameters.
Syntax: [access modifier] data type this [data type identifier]
{
Get {};
Set {};
}
The following is an example of a video that describes how to search photos by index and name.
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace ConsoleApplication11 {class Program {static void Main (string [] args) {Ablum MyAblum1 = new Ablum (2 ); // create an album with a capacity of 2 // create two photos Photo first = new Photo ("Xiao Chu"); Photo second = new Photo ("Xiao Wang "); // load the Photo MyAblum1 [0] = first; MyAblum1 [1] = second; // retrieve Photo testPhots = MyAblum1 [0] by index; Console. writeLine (testPhots. title); // retrieve Photo testPhotos = MyAblum1 ["John"]; Console. writeLine (testPhotos. title) ;}} class Photo {private string PhotoTitle; // declare a private variable // create a default constructor public Photo () {PhotoTitle = "Chu Guangming ";} public Photo (string title) // constructor with a parameter {PhotoTitle = title;} public string Title // specify the return value {get {return PhotoTitle ;}}} class Ablum {Photo [] photos; // defines the array public Ablum () {photos = new Photo [3]; // defines the number of default elements of the array} public Ablum (int Capacity) // any number of elements in the array {photos = new Photo [Capacity];} public Photo this [int index] // Photo indexer with int parameter {get {// access if (index <0 | index> = photos. length) // verify the index range {Console. writeLine ("index problems"); return null; // use null to indicate failure} return photos [index]; // for valid indexes, returned photo} set {if (index <0 | index> = photos. length) {Console. writeLine ("index problems"); return;} photos [index] = value ;}} public Photo this [string title] // The Photo indexer with the string parameter {get {foreach (Photo p in photos) // traverses all the photos in the array {if (p. title = title) // compare the Title in the photo with the index parameters. return p;} Console. writeLine ("not found"); return null ;}}}}