switch function c# code example
Example 1: c# switch
using System;
public class Example
{
public static void Main()
{
int caseSwitch = 1;
switch (caseSwitch)
{
case 1:
Console.WriteLine("Case 1");
break;
case 2:
Console.WriteLine("Case 2");
break;
default:
Console.WriteLine("Default case");
break;
}
}
}
Example 2: c# switch case
using System;
namespace DecisionMaking
{
class Program
{
static void Main(string[] args)
{
char grade = 'B';
switch (grade)
{
case 'A':
Console.WriteLine("Excellent!");
break;
case 'B':
case 'C':
Console.WriteLine("Well done");
break;
case 'D':
Console.WriteLine("You passed");
break;
case 'F':
Console.WriteLine("Better try again");
break;
default:
Console.WriteLine("Invalid grade");
break;
}
Console.WriteLine("Your grade is {0}", grade);
Console.ReadLine();
}
}
}
=======OUTPUT========
Well done
Your grade is B
Example 3: switch expression c#
var switchValue = 3;
var resultText = switchValue switch
{
1 or 2 or 3 => "one, two, or three",
4 => "four",
5 => "five",
_ => "unknown",
};