Indexers in C# allow us to interact with instances of a class using brackets ([]), just like with arrays.
Let's see how to use them on a practical example.
Firstly, we define a class called Book.
public class Book
{
public string Title { get; set; }
public Book(string title)
{
Title = title;
}
}
Then, we can define a class containing a list of Books called BookCollection.public class BookCollection
{
private List _list = new List();
public Book this[string title]
{
get { return _list.Find(x => x.Title == title); }
set { _list.Add(new Book(title)); }
}
}
As you can see, it also contains an indexer definition. It is using a string as a parameter, and returning a Book object. Inside of the indexer definition we declare what will happen both on accesing the data (get) and setting the data (set). Next, we can try the indexer out inside the Main method.
public class Program
{
public static void Main()
{
var book = new Book("Harry Potter");
var collection = new BookCollection();
collection["Harry Potter"] = book;
Console.WriteLine(collection["Harry Potter"].Title);
}
}