How to print weekday in C# using switch

Overview

In C#, a weekday represents any number from 0 to 6. With this logic, we can say that 0 stands for Sunday, 1 for Monday, and so on.

Syntax

Below is the syntax of the switch statement:

switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
Syntax for Switch Statement in C#

Parameters

expression: This is evaluated once. It could be any expression that evaluates to a value that will be used by the case keyword.

case x, case y: These are values the expression evaluates. For every value, there is a case associated with it. Thus, every case has its own code block.

break: This means to stop the execution of a code block once it has been done for the particular case.

default: This is used when the expression does not evaluate to any value like x or y.

Example

Following is the switch use case for days of the week:

using System;
namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
// create a random week day value
Random rnd = new Random();
int wday = rnd.Next(0,6); // between 0 and 6
switch (wday)
{
case 0:
Console.WriteLine("Sunday");
break;
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
default:
Console.WriteLine("Something went wrong!");
break;
}
}
}
}

Explanation

  • Line 10: We create a random instance.
  • Line 11: We create a weekday value which is an integer. Its value is between 0 to 6, which are the 7 weekdays.
  • Line 12: We evaluate any value of the wday variable and the appropriate case is assigned once it is evaluated. For each case , we print the corresponding weekday to the console.

Free Resources