Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

C# Switch:


Certainly! In C#, the switch statement is a control flow statement that allows you to execute different blocks of code based on the value of an expression. It's often used as an alternative to long chains of if-else statements when you have multiple conditions to check. Here's a simple explanation with an example:

  1. Syntax: The switch statement consists of the switch keyword followed by the expression to evaluate, curly braces {}, and a series of case labels.

  2. case labels: Each case label represents a possible value of the expression. When the expression matches a case label, the corresponding block of code executes.

  3. default case: Optionally, you can include a default case, which executes if none of the case labels match the expression.

Here's an example that demonstrates the usage of the switch statement:

Example

using System;

class Program
{
static void Main()
{
int dayOfWeek = 3; // Let's assume it's Wednesday

switch (dayOfWeek)
{
case 1:
Console.WriteLine("It's Monday.");
break;
case 2:
Console.WriteLine("It's Tuesday.");
break;
case 3:
Console.WriteLine("It's Wednesday.");
break;
case 4:
Console.WriteLine("It's Thursday.");
break;
case 5:
Console.WriteLine("It's Friday.");
break;
case 6:
Console.WriteLine("It's Saturday.");
break;
case 7:
Console.WriteLine("It's Sunday.");
break;
default:
Console.WriteLine("Invalid day.");
break;
}
}
}

Explanation:

This is a simple example of how you can use the switch statement to execute different blocks of code based on the value of an expression.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java