C# logical operators

C# logical operators

As with comparison operators, you can also test for True or False values with logical operators.

Logical operators are used to combine two or more conditions/constraints or to complement the evaluation of the original condition in consideration. They are described below:

  • Logical AND: The ‘&&’ operator returns true when both the conditions in consideration are satisfied. Otherwise it returns false.
  • Logical OR: The ‘||’ operator returns true when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false.
  • Logical NOT: The ‘!’ operator returns true the condition in consideration is not satisfied. Otherwise it returns false.

We normally use logic operators to combine conditions.

In this example, the FieldTrip method returns true if it's rainy or sunny.

As long as it's not also windy:

bool FieldTrip (bool rainy, bool sunny, bool windy)
{
       return !windy && (rainy || sunny);
}

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:

OperatorNameDescriptionExample
&&Logical andReturns True if both statements are true(A && B) is false
||Logical orReturns True if one of the statements is true(A || B) is true
!Logical notReverse the result, returns False if the result is true!(A && B) is true

 

C# Logical Operators Example

Following is the example of using the Logical Operators in c# programming language:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true, b = false, result;

            // AND operator
            result = a && b;
            Console.WriteLine("AND Operator: " + result);

            // OR operator
            result = a || b;
            Console.WriteLine("OR Operator: " + result);

            // NOT operator
            result = !a;
            Console.WriteLine("NOT Operator: " + result);
            Console.ReadLine();
        }       
    }
}

Output:

C# Logical Operators Example