Switch operatorida default amalini yozish shart emas, chunki u berilgan qiymatning tanlangan birorta qiymatga mos kelmaganda bajariladigan amallarni o’z ichiga oladi. Agarda berilgan qiymat birorta tanlangan qiymatga mos kelsa, u holda case amalidan keyin bajariladigan amallar (ular bir nechta bo’lsa, { } orasiga olinadi) bajariladi, so’ng break amali switch operatorining ishini shu joyda to’xtatadi va switch operatoridan keyin keladigan operator ishini davom ettiradi.
C va C++ tillarida keyingi case amaliga avtomatik o’tishingiz mumkin, agarda oldingi case amalining oxirida break yoki goto operatorlari yozilmagan bo’lsa. Shunday qilib, C va C++ da quyidagicha yozish mumkin :
Case : statement 1 ; Case : statement 2; Break ; Bu misolda statement 1 dan so’ng statement 2 ga avtomatik tarzda o’tiladi (C++ da). C# da bu dastur ishlamaydi, chunki C# tili sintaksisida case1 dan case2 ga ikki xil vaziyatda o’tish mumkin : agarda birinchi amal bo’sh bo’lsa (case dan so’ng hech qanday qiymat tekshiriladi) yoki break, goto operatorlari yordamida. Har bir case operatori o’zida break amalini ushlab turishi lozim. Masalan:
{
switch (a ) case 10: Console.WriteLine("a= 10" ) ; break; case 20: Console.WriteLine("a=20"); break; case 30: Console.WriteLine("a= 30"); break; }
user = Convert.Tolnt32(Console.ReadLine( )); switch(user) case 0:
Console.WriteLine("Salom User1"); break; case 1 :
Console.WriteLine("Salom User2"); break; case 2:
Console.WriteLine("Salom User3"); break; default:
Console.WriteLine("Salom yangi foydalanuvchi"); break; }
Quyida iqtisodiy masalani yechish usuli berilgan :
using System;
namespace C_Sharp_Programing
{
class Part
{
public static void Main() {
Console.WriteLine("1: mahsulot nomini kiriting,n2: mahsulot sonini kiriting"); int Choice = Convert.Tolnt32(Console.ReadLine()); switch (Choice) case 1 : string Kane;
Console.Write("Mahsulot nomini kiriting " ) ; Name = Console.ReadLine(); break; case 2: int Count;
Console.Write("Mahsulot sonini kiriting " ) ; Name = Console.ReadLine(); Count = Convert.Tolnt32(Console.ReadLine()) ; break; default: