Sometimes you need to look at one value and choose one option from many possibilities. For example, you may want to display the day name based on the day number.
That is where switch is used. It takes a single value and runs the matching block of code.
int gun = 2;
switch (gun)
{
case 1:
Console.WriteLine("Pazartesi");
break;
case 2:
Console.WriteLine("Salı");
break;
}
Writing many if / else if blocks for the same variable can make the code longer. In equality-based checks, switch often looks cleaner.
So if you are checking which option a single value matches, switch can improve readability.
Each case represents one possible match. If the value matches that case, the related block runs.
In most classic uses, a break statement is written at the end of the case. This exits the switch structure.
string mevsim = "Yaz";
switch (mevsim)
{
case "Kış":
Console.WriteLine("Mont giy.");
break;
case "Yaz":
Console.WriteLine("Tişört giy.");
break;
}
Sometimes none of the cases match. That is what the default block is for.
Default means 'if none of these match, do this'. You can think of it as a safety net.
int ay = 15;
switch (ay)
{
case 1:
Console.WriteLine("Ocak");
break;
case 2:
Console.WriteLine("Şubat");
break;
default:
Console.WriteLine("Geçersiz ay");
break;
}
Switch offers a very clean structure, but it is not meant for every situation. When used in the right place, it simplifies the code.