C# - Logical Operators



What Are Logical Operators in C#?

C# logical operators evaluate multiple conditions and return either true or false. When you need to check multiple conditions, you can combine them using these operators. These operators are helpful for decision-making, loops, and data validation in programming.

List of Logical Operators

Following table shows all the logical operators supported by C#. Assume variable A holds Boolean value true and variable B holds Boolean value false, then −

Operator Symbol Description Example
Logical AND && Called Logical AND operator. If both the operands are non zero then condition becomes true. (A && B) is false.
Logical OR || Called Logical OR Operator. If any of the two operands is non zero then condition becomes true. (A || B) is true.
Logical NOT ! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(A && B) is true.

Example of C# Logical Operators

The following example demonstrates all the logical operators available in C# −

using System;

namespace OperatorsAppl {
   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");
         }
         
         /* lets change the value of  a and b */
         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();
      }
   }
}

When the above code is compiled and executed, it produces the following result −

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

More Examples of Logical Operators

Example 1: Using Logical Operators in if Conditions

In this example, we are checking if a person is allowed to enter based on age and ID verification.

using System;

class Program
{
    static void Main()
    {
        int age = 20;
        bool hasID = true;

        if (age >= 18 && hasID)
        {
            Console.WriteLine("Allowed to enter.");
        }
        else
        {
            Console.WriteLine("Entry denied.");
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Allowed to enter.

Example 2: Logical AND (&&)

In this example, we are checking if a student is eligible for a scholarship based on score and exam pass status.

using System;

class Program
{
    static void Main()
    {
        int score = 85;
        bool passedExam = true;

        if (score >= 80 && passedExam)
        {
            Console.WriteLine("Eligible for scholarship.");
        }
        else
        {
            Console.WriteLine("Not eligible.");
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Eligible for scholarship.

Example 3: Logical OR (||)

In this example, we are checking if a person is granted access based on either a VIP pass or a regular ticket.

using System;

class Program
{
    static void Main()
    {
        bool hasVIPPass = false;
        bool hasRegularTicket = true;

        if (hasVIPPass || hasRegularTicket)
        {
            Console.WriteLine("Access granted.");
        }
        else
        {
            Console.WriteLine("Access denied.");
        }
    }
}

When the above code is compiled and executed, it produces the following result −

Access granted.

Example 4: Logical NOT (!)

In this example, we are checking whether it is not raining to decide if we should go outside.

using System;

class Program
{
    static void Main()
    {
        bool isRaining = false;

        if (!isRaining)
        {
            Console.WriteLine("Go outside!");
        }
        else
        {
            Console.WriteLine("Stay indoors.");
        }
    }
}

In this example, we are checking whether it is not raining to decide if we should go outside.

Go outside!

Use Cases

The following are some of the use cases of logical operators:

Example 5: User Login Validation

In this example, we are validating user credentials to allow or deny login.

using System;

class Program
{
    static void Main()
    {
        string username = "admin";
        string password = "pass123";

        if (username == "admin" && password == "pass123")
        {
            Console.WriteLine("Login successful.");
        }
        else
        {
            Console.WriteLine("Invalid credentials.");
        }
    }
}

In this example, we are checking whether it is not raining to decide if we should go outside.

Login successful.

Example 6: Checking Store Discount Eligibility

In this example, we are checking if a customer is eligible for a discount based on membership status or purchase amount.

using System;

class Program
{
    static void Main()
    {
        bool isMember = true;
        double purchaseAmount = 120.0;

        if (isMember || purchaseAmount > 100)
        {
            Console.WriteLine("Discount applied.");
        }
        else
        {
            Console.WriteLine("No discount available.");
        }
    }
}

In this example, we are checking whether it is not raining to decide if we should go outside.

Discount applied.

Best Practices

The following are the best practices for using logical operators in C#:

  • You should use parentheses to group conditions like ((x && y) || z).
  • You should simplify expressions, e.g., use if (!isReady) instead of if (isReady == false).
  • You must avoid redundant checks, e.g., use if (x) instead of if (x == true).
  • You should always test edge cases when combining conditions.
Advertisements