Bazen tek bir değere bakıp birçok ihtimalden birini seçmen gerekir. Örneğin haftanın gün numarasına göre gün adını göstermek isteyebilirsin.
Böyle durumlarda switch yapısı kullanılır. Tek bir değeri alır ve uygun eşleşmeye göre ilgili kodu çalıştırır.
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;
}
Aynı değişken için çok sayıda if / else if yazmak kodu uzatabilir. Özellikle eşitlik bazlı kontrollerde switch daha temiz görünür.
Yani bir değerin hangi seçeneğe denk geldiğini kontrol ediyorsan switch okunabilirliği artırabilir.
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.
Her case, olası bir eşleşmeyi temsil eder. Değer o case ile aynıysa ilgili blok çalışır.
Çoğu klasik kullanımda case sonunda break yazılır. Bu, switch yapısından çıkılmasını sağlar.
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;
}
Bazen hiçbir case eşleşmez. Böyle durumlar için default bloğu vardır.
Default, 'bunların hiçbiri değilse bunu yap' demektir. Güvenlik ağı gibi düşünebilirsin.
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 çok temiz bir yapı sunar ama her yerde kullanılmaz. Doğru yerde kullanıldığında kodu sadeleştirir.
Switch offers a very clean structure, but it is not meant for every situation. When used in the right place, it simplifies the code.