โครงสร้างการตัดสินใจต้องการให้โปรแกรมเมอร์ระบุเงื่อนไขอย่างน้อยหนึ่งเงื่อนไขที่จะประเมินหรือทดสอบโดยโปรแกรม พร้อมกับคำสั่งหรือคำสั่งที่จะดำเนินการหากเงื่อนไขถูกกำหนดให้เป็นจริง และทางเลือกอื่น ๆ ที่จะดำเนินการถ้าเงื่อนไข ถูกกำหนดให้เป็นเท็จ
การตัดสินใจในภาษา C# ประกอบด้วยคำสั่ง if คำสั่ง if-else คำสั่ง switch เป็นต้น
เรามาดูตัวอย่างคำสั่ง if ใน C# กัน
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int x = 5;
// if statement
if (x < 20) {
/* if condition is true then print the following */
Console.WriteLine("x is less than 20");
}
Console.WriteLine("value of x is : {0}", x);
Console.ReadLine();
}
}
} ผลลัพธ์
x is less than 20 value of x is : 5
เรามาดูตัวอย่างคำสั่ง if-else ใน C# กัน ในกรณีนี้ หากเงื่อนไขแรกเป็นเท็จ เงื่อนไขในคำสั่ง else จะถูกตรวจสอบ
ตัวอย่าง
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int x = 100;
/* check the boolean condition */
if (x < 20) {
/* if condition is true then print the following */
Console.WriteLine("x is less than 20");
} else {
/* if condition is false then print the following */
Cohttp://tpcg.io/HoaKexnsole.WriteLine("x is not less than 20");
}
Console.WriteLine("value of a is : {0}", x);
Console.ReadLine();
}
}
} ผลลัพธ์
x is not less than 20 value of a is : 100