[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Take actions depending on the day of the week in C#

[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. switch (DateTime.Now.DayOfWeek) { case DayOfWeek.Monday: lblGreeting1.Text = "It's Manic Monday!"; break; case DayOfWeek.Tuesday: lblGreeting1.Text = "It's Terriffic Tuesday"; break; case DayOfWeek.Wednesday: lblGreeting1.Text = "It's Happy Hump Day!"; break; case DayOfWeek.Thursday: lblGreeting1.Text = "It's Thirsty Thursday"; break; case DayOfWeek.Friday: lblGreeting1.Text = "It's Freaky Friday"; break; case DayOfWeek.Saturday: lblGreeting1.Text = "It's Satisfying Saturday"; break; case DayOfWeek.Sunday: lblGreeting1.Text = "It's Sleepy Sunday"; break; } // Set a label by using an array. string[] greetings = { "Sleepy Sunday", "Manic Monday!", "Terriffic Tuesday", "Happy Hump Day!", "Thirsty Thursday", "Freaky Friday", "Satisfying Saturday", }; 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.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.