"switch" Statements - Example

This section provides a tutorial example on how to use 'switch' statements to print business hours based on today's date.

The following program shows how a "switch" statement is used to print a specific message depending on which day of week it is today:

// Switches.cs
// Copyright (c) 2006 HerongYang.com. All Rights Reserved.

class Switches {
   public static void Main() {
      int today;
      string message;

      today = (int) System.DateTime.Today.DayOfWeek;
      switch (today) {
         case 1:
            message = "Today is Monday. We are open until 5 p.m.";
            break;
         case 2:
            message = "Today is Tuesday. We are open until 5 p.m.";
            break;
         case 3:
            message = "Today is Wednesday. We are open until 5 p.m.";
            break;
         case 4:
            message = "Today is Thursday. We are open until 7 p.m.";
            break;
         case 5:
            message = "Today is Friday. We are open until 7 p.m.";
            break;
         default:
            message = "Sorry, we are closed on weekends.";
            break;
      }
      System.Console.WriteLine(message);
   }
}

Output:

Sorry, we are closed on weekends.

Note that we are using the DateTime structure provided by the C# compiler to get the day of week of today, casted to the "int" type. By checking the reference manual, we can see that the day of week has a value of 0 to 6, representing Sunday to Saturday, respectively. Of course, the above output was generated on a Sunday.

Table of Contents

 About This Book

 Introduction of C# (C Sharp)

 Data Type and Variables

Logical Expressions and Conditional Statements

 Logical Expressions

 "if" Statements

 "if" Statements - Example

 "switch" Statements

"switch" Statements - Example

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

 Class Features

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

 Multithreading in C#

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Archived Tutorials

 References

 Full Version in PDF/ePUB