เพื่อเปรียบเทียบค่าสองค่าใน C# ให้ใช้ Relational operators
| Operator | Description |
|---|---|
| == | ตรวจสอบว่าค่าของสอง operand เท่ากันหรือไม่ ถ้าใช่ condition เป็น true |
| != | ตรวจสอบว่าค่าของสอง operand ไม่เท่ากัน ถ้าไม่เท่ากัน condition เป็น true |
| > | ตรวจสอบว่า operand ซ้ายมากกว่า operand ขวา ถ้าใช่ condition เป็น true |
| < | ตรวจสอบว่า operand ซ้ายน้อยกว่า operand ขวา ถ้าใช่ condition เป็น true |
| >= | ตรวจสอบว่า operand ซ้ายมากกว่าหรือเท่ากับ operand ขวา |
| <= | ตรวจสอบว่า operand ซ้ายน้อยกว่าหรือเท่ากับ operand ขวา |
ตัวอย่าง
using System;
class Program {
static void Main(string[] args) {
int a = 21;
int b = 10;
if (a == b) Console.WriteLine("Line 1 - a is equal to b");
else Console.WriteLine("Line 1 - a is not equal to b");
if (a < b) Console.WriteLine("Line 2 - a is less than b");
else Console.WriteLine("Line 2 - a is not less than b");
if (a > b) Console.WriteLine("Line 3 - a is greater than b");
else Console.WriteLine("Line 3 - a is not greater than b");
a = 5; b = 20;
if (a <= b) Console.WriteLine("Line 4 - a is either less than or equal to b");
if (b >= a) Console.WriteLine("Line 5 - b is either greater than or equal to a");
}
}
ผลลัพธ์
Line 1 - a is not equal to b Line 2 - a is not less than b Line 3 - a is greater than b Line 4 - a is either less than or equal to b Line 5 - b is either greater than or equal to a