Indexers Real-Time Example in CSharp
Back to: C# .NET Tutorial
Here is a lesson providing a real-time example of using indexers in C#, covering all essential topics with various examples in a comprehensive 1000-word article.
Exploring Indexers in C#: Real-Time Example
Indexers in C# allow instances of a class or struct to be accessed using array notation. Let’s delve into a real-time example to understand the practical application of indexers and explore their implementation in different scenarios.
Understanding the Need for Indexers
Consider a scenario where you have a custom collection class, ‘BookCollection,’ which contains a list of books. With the help of an indexer, you can access books in the collection using array notation. Here’s an example illustrating the implementation of an indexer:
using System; class BookCollection { private string[] books = new string[5]; public string this[int index] { get { if (index < 0 || index >= books.Length) throw new IndexOutOfRangeException("Index out of range"); return books[index]; } set { if (index < 0 || index >= books.Length) throw new IndexOutOfRangeException("Index out of range"); books[index] = value; } } } class Program { static void Main() { BookCollection myBooks = new BookCollection(); myBooks[0] = "Book1"; myBooks[1] = "Book2"; Console.WriteLine("My Books:"); for (int i = 0; i < 2; i++) { Console.WriteLine(myBooks[i]); } } }
Applying Indexers in Real-Time Scenarios
Indexers can be applied to various real-time scenarios, such as managing a database of students in a school. By using an indexer, you can access students’ information based on their unique IDs. Here’s an example depicting the implementation of an indexer for a student database:
using System; using System.Collections.Generic; class StudentDatabase { private Dictionary<int, string> students = new Dictionary<int, string>(); public string this[int studentId] { get { if (!students.ContainsKey(studentId)) throw new KeyNotFoundException("Student ID not found"); return students[studentId]; } set { if (students.ContainsKey(studentId)) students[studentId] = value; else students.Add(studentId, value); } } } class Program { static void Main() { StudentDatabase database = new StudentDatabase(); database[1001] = "John Doe"; database[1002] = "Jane Smith"; Console.WriteLine("Student Database:"); Console.WriteLine("Student 1001: " + database[1001]); Console.WriteLine("Student 1002: " + database[1002]); } }
By grasping the practical applications of indexers in C#, developers can efficiently manage and access data in custom collections, databases, and various other real-time scenarios, simplifying data retrieval and enhancing code functionality.