C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
"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
►Logical Expressions and Conditional Statements
►"switch" Statements - Example
Visual C# 2010 Express Edition
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation