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

[day of the week]

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!";
        case DayOfWeek.Tuesday:
            lblGreeting1.Text = "It's Terriffic Tuesday";
        case DayOfWeek.Wednesday:
            lblGreeting1.Text = "It's Happy Hump Day!";
        case DayOfWeek.Thursday:
            lblGreeting1.Text = "It's Thirsty Thursday";
        case DayOfWeek.Friday:
            lblGreeting1.Text = "It's Freaky Friday";
        case DayOfWeek.Saturday:
            lblGreeting1.Text = "It's Satisfying Saturday";
        case DayOfWeek.Sunday:
            lblGreeting1.Text = "It's Sleepy Sunday";

    // 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 Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in variables and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.