Title: Take actions depending on the day of the week in C#
When the program starts, it uses the following code to display a different message in two different ways for each day of the week.
// Display a message that depends on the day of the week.
private void Form1_Load(object sender, EventArgs e)
// Set the label with a switch statement.
lblGreeting1.Text = "It's Manic Monday!";
lblGreeting1.Text = "It's Terriffic Tuesday";
lblGreeting1.Text = "It's Happy Hump Day!";
lblGreeting1.Text = "It's Thirsty Thursday";
lblGreeting1.Text = "It's Freaky Friday";
lblGreeting1.Text = "It's Satisfying Saturday";
lblGreeting1.Text = "It's Sleepy Sunday";
// Set a label by using an array.
string greetings =
"Happy Hump Day!",
lblGreeting2.Text = "It's " + greetings[(int)DateTime.Now.DayOfWeek];
The program starts by using a switch statement to set a label's value depending on the day of the week. This code is somewhat long but it's very easy to understand.
Next the program creates an array of greetings, one for each day of the week. The array starts with Sunday's message because DayOfWeek.Sunday = 0 and the other days of the week follow numerically. The program then uses the current day's DayOfWeek value as an index into the array to display the corresponding message.
The second version is more concise but it's a little harder to understand than the code that uses switch. It also relies on the fact that DayOfWeek.Sunday = 0, which you just have to know from the documentation.
Download the example to experiment with it and to see additional details.