Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Logical Operators (ออเปอเรเตอร์เชิงตรรกะ) ใน C#

Logical operators ใช้กับค่า Boolean มี 3 ตัวใน C#:

OperatorDescription
&&Logical AND - ทั้งสอง operand เป็น true ถึงได้ true
||Logical OR - operand ไหนตัวหนึ่งเป็น true ก็ได้ true
!Logical NOT - กลับสถานะตรรกะ true→false, false→true

ตัวอย่าง

using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            bool a = true;
            bool b = true;
            
            if (a && b) Console.WriteLine("Line 1 - Condition is true");
            if (a || b) Console.WriteLine("Line 2 - Condition is true");
            
            a = false; b = true;
            if (a && b) Console.WriteLine("Line 3 - Condition is true");
            else Console.WriteLine("Line 3 - Condition is not true");
            
            if (!(a && b)) Console.WriteLine("Line 4 - Condition is true");
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

Line 1 - Condition is true
Line 2 - Condition is true
Line 3 - Condition is not true
Line 4 - Condition is true