0
0
C Sharp (C#)programming~30 mins

Indexer with custom types in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Indexer with Custom Types in C#
📖 Scenario: You are creating a simple library system to manage books. Each book has a unique ID and a title. You want to access books easily using their ID.
🎯 Goal: Build a class Library that stores books and allows accessing them using an indexer with a custom type BookID.
📋 What You'll Learn
Create a struct called BookID with an integer field Id
Create a class called Book with a string property Title
Create a class called Library that stores books in a dictionary with BookID as key
Add an indexer in Library to get and set Book objects by BookID
Demonstrate adding and retrieving books using the indexer
💡 Why This Matters
🌍 Real World
Indexers with custom types are useful when you want to access complex data collections using meaningful keys, like IDs or codes.
💼 Career
Understanding indexers and custom types helps in building clean, readable code for managing data in software development jobs.
Progress0 / 4 steps
1
Create the BookID struct and Book class
Create a struct called BookID with a public integer field Id. Also create a class called Book with a public string property Title that has get and set accessors.
C Sharp (C#)
Need a hint?

Think of BookID as a simple label for books. The Book class holds the book's title.

2
Create the Library class with a dictionary to store books
Create a class called Library. Inside it, create a private dictionary called books that uses BookID as key and Book as value. Initialize books in the constructor.
C Sharp (C#)
Need a hint?

The dictionary will help you store and find books by their BookID.

3
Add an indexer to Library to get and set books by BookID
Inside the Library class, add a public indexer that takes a BookID parameter and returns a Book. The indexer should get the book from the books dictionary if it exists, or return null if not. It should also allow setting a book for a given BookID.
C Sharp (C#)
Need a hint?

The indexer lets you write library[bookId] to get or set a book.

4
Add books and print their titles using the indexer
Create a Library object called library. Add two books with BookID values 1 and 2 and titles "C# Basics" and "Advanced C#" using the indexer. Then print the titles of these books using the indexer.
C Sharp (C#)
Need a hint?

Use the indexer to add and then print book titles by their BookID.