Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Toán tử logic (Logical Operators) trong C#

Toán tử logic dùng với giá trị Boolean. C# có 3 toán tử logic chính:

Toán tửTênMô tả
&&Logical ANDTrue nếu cả hai operand true
||Logical ORTrue nếu ít nhất một operand true
!Logical NOTĐảo ngược giá trị logic

Short-circuit evaluation: && và || đánh giá lùi (short-circuit): nếu operand đầu đủ quyết định kết quả, operand sau không được đánh giá.

Ví dụ

using System;

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

Kết quả

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

Toán tử bitwise tương ứng: &, |, ^ (XOR), ~ (NOT) - đánh giá tất cả operand, dùng cho bit flag.