Switch/Case Yapısı
switch _deyimi,_ tek bir ifadenin değerine göre sınırsız sayıda çalıştırma yolu belirlemeyi sağlayan bir anahtar kelimedir(keyword).
Birden fazla koşula(if) bağlı programlarda if/else yapısı yerine kullanılabilir fakat if/else kadar her zaman esnekliğe sahip değildir.
c# da her case den sonar break kullanmamız gerekir.
Örnek
using System;
namespace switchCase
{
class MainClass
{
public static void Main(string[] args)
{
int not;
int ogrenciSayısı = 0;
int notlarınToplamı = 0;
int notA = 0;
int notB = 0;
int notC = 0;
int notD = 0;
int notF = 0;
Console.WriteLine("Öğrencilerin notlarını giriniz.");
string ekrandanAlınanDeğer = Console.ReadLine();
while(ekrandanAlınanDeğer != null)
{
not = int.Parse(ekrandanAlınanDeğer);
notlarınToplamı += not;
ogrenciSayısı++;
switch (not/10)
{
case 10:
case 9 :
Console.WriteLine("A notu işlendi");
notA++;
break;
case 8:
Console.WriteLine("B notu işlendi");
notB++;
break;
case 7:
Console.WriteLine("C notu işlendi");
notC++;
break;
case 6:
Console.WriteLine("D notu işlendi");
notD++;
break;
default:
Console.WriteLine("F notu işlendi");
notF++;
break;
}
ekrandanAlınanDeğer = Console.ReadLine();
}
double ortalama = (double)notlarınToplamı / ogrenciSayısı;
if (ogrenciSayısı != 0)
{
Console.WriteLine($"öğrenci sayısı : {ogrenciSayısı} ortalama: {ortalama}");
}
else
{
Console.WriteLine("öğrenci notu girilmedi");
}
}
}
}
Örnek
using System;
namespace whileSwitchCase
{
class MainClass
{
public static void Main(string[] args)
{
string secim;
do
{
Console.WriteLine("Adres Defteri \n");
Console.WriteLine("E - Adres ekle");
Console.WriteLine("S - Adres sil");
Console.WriteLine("G - Adres güncelle");
Console.WriteLine("K - Adrese bak");
Console.WriteLine("Q - cıkıs");
Console.Write("(E,S,G,K,Q) : ");
secim = Console.ReadLine();
// int a = 5;
switch (secim)
{
// case "e":
case "E":
Console.WriteLine("adres ekle\n");
break;
//case "S":
case "s":
Console.WriteLine("adres sil\n");
break;
//case "g":
case "G":
Console.WriteLine("adres güncelle\n");
break;
//case "k":
case "K":
Console.WriteLine("adres defterini kontrol et\n");
break;
//case "q":
case "Q":
Console.WriteLine("adres defterinden çıktın\n");
break;
default:
Console.WriteLine("{0} hatalı giriş.",secim);
break;
}
} while (secim!="Q" && secim!="q") ;
}
}
}