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

Indexer declaration in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Indexer Declaration in C#
📖 Scenario: Imagine you are creating a simple class to store and access the names of days in a week by their number. You want to use an indexer so that you can get or set the day name using the day number like an array.
🎯 Goal: Build a class called WeekDays that uses an indexer to get and set day names by their index (0 to 6).
📋 What You'll Learn
Create a class called WeekDays with a private string array of length 7.
Add an indexer to WeekDays that takes an int index and returns or sets the day name at that index.
Use the indexer to set the names of the days from Sunday to Saturday.
Print the day name at index 3 using the indexer.
💡 Why This Matters
🌍 Real World
Indexers let you create classes that behave like arrays or lists, making your code easier to read and use.
💼 Career
Many software jobs require creating custom data structures with indexers to simplify data access and improve code clarity.
Progress0 / 4 steps
1
Create the WeekDays class with a private string array
Create a class called WeekDays with a private string array called days of length 7.
C Sharp (C#)
Need a hint?

Use private string[] days = new string[7]; inside the class.

2
Add an indexer to get and set day names by index
Inside the WeekDays class, add an indexer with public string this[int index] that gets and sets the value in the days array at index.
C Sharp (C#)
Need a hint?

The indexer looks like a property but uses this[int index].

3
Set the names of the days using the indexer
Create a WeekDays object called week and use the indexer to set the days: Sunday at index 0, Monday at 1, Tuesday at 2, Wednesday at 3, Thursday at 4, Friday at 5, and Saturday at 6.
C Sharp (C#)
Need a hint?

Use week[index] = "DayName"; to set each day.

4
Print the day name at index 3 using the indexer
Write a Console.WriteLine statement to print the day at index 3 from the week object using the indexer.
C Sharp (C#)
Need a hint?

Use Console.WriteLine(week[3]); to print the day at index 3.