Relational และ comparison operators
ตัวดำเนินการเปรียบเทียบ (comparison) และความสัมพันธ์ (relational) ถูกใช้ในการสร้าง expression กับตัวแปรและค่าคงที่ โดยผลลัพธ์ของ expression จะมีแค่เพียง true หรือ false เท่านั้น มันมักจะใช้เพื่อสร้างเงื่อนไขเพื่อใช้กับคำสั่งในการเปรียบเทียบ เช่น if else, switch, while, do-while และ for เป็นต้น
ตารางของ relational และ comparison operators ในภาษา C#
Operater |
Example |
Result |
== |
a == b |
true if `a` equal to `b`, otherwise false |
!= |
a != b |
true if `a` not equal to `b`, otherwise false |
< |
a < b |
true if `a` less than `b`, otherwise false |
> |
a > b |
true if `a` greater than `b`, otherwise false |
<= |
a <= b |
true if `a` less than or equal to `b`, otherwise false |
>= |
a >= b |
true if `a` greater than or equal to `b`, otherwise false |
ตัวอย่างในการใช้ตัวดำเนินการเปรียบเทียบ
int n = 10;
if (n % 2 == 0) {
Console.WriteLine(“n is even number.”);
}
int x = 6, y = 2;
if (x < y) {
Console.WriteLine(“x is less than y”);
}
ผลลัพธ์เมื่อรันโปรแกรม
n is even number.
จากตัวอย่างข้างบน ได้มีการใช้ตัวดำเนินการเปรียบเทียบ == เพื่อตรวจสอบถ้า n นั้นเป็นจำนวนคู่ แล้วโปรแกรมก็จะทำงานในบล็อคคำสั่งของ if ต่อมา ได้มีการใช้ตัวดำเนินการเปรียบเทียบน้อยกว่า < เพื่อตรวจสอบว่าถ้า x น้อยกว่า y เนื่องจาก x ไม่ได้น้อยกว่า y ดังนั้นโปรแกรมจึงไม่ทำงานในบล็อคคำสั่งของ if