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:
&&
’ operator returns true
when both the conditions in consideration are satisfied. Otherwise it returns false
.||
’ operator returns true
when one (or both) of the conditions in consideration is satisfied. Otherwise it returns false
.!
’ 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:
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns True if both statements are true | (A && B) is false |
|| | Logical or | Returns True if one of the statements is true | (A || B) is true |
! | Logical not | Reverse the result, returns False if the result is true | !(A && B) is true |
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: