Here we will learn logical operators in c# with examples, different type of logical operators (Logical AND, Logical OR, Logical NOT) in c# with examples and how to use logical operators in c# to perform logical operations on defined operands with examples
In c#, Logical Operators are used to perform the logical operation between two operands like AND, OR and NOT based on our requirements. The Logical Operators will always work with Boolean expressions (true or false) and return Boolean values.
The operands in logical operators must always contain only Boolean values otherwise Logical Operators will throw an error.
Following table lists the different type of operators available in c# relational operators.
|Operator||Name||Description||Example (a = true, b = false)|
|&&||Logical AND||It return true if both operands are non zero.||a && b (false)|
|||||Logical OR||It returns true if any one operand become a non zero.||a || b (true)|
|!||Logical NOT||It return the reverse of logical state that means if both operands are non zero then it will return false.||!(a && b) (true)|
If we use Logical AND, OR operators in c# applications, those will return the result like as shown below for different inputs.
If you observe above table, if any one operand value become false, then the logical AND operator will return false, same way the logical OR operator will return true, if any one operand value become true.
In case if we use Logical NOT operator in our c# applications, it will return the results like as shown below for different inputs.
If you observe above table, the Logical NOT operator will always return the reverse value of operand like if operand value true, then the Logical NOT operator will return false and vice versa.
Following is the example of using the Logical Operators in c# programming language.
static void Main(string args)
int x = 15, y = 10;
bool a = true, result;
// AND operator
result = (x <= y) && (x > 10);
Console.WriteLine("AND Operator: " + result);
// OR operator
result = (x >= y) || (x < 5);
Console.WriteLine("OR Operator: " + result);
result = !a;
Console.WriteLine("NOT Operator: " + result);
Console.WriteLine("Press Any Key to Exit..");
If you observe above code, we used a logical operators (AND, OR, NOT) to perform different operations on defined operands.
When we execute above c# program, we will get the result like as shown below.
This is how we can use logical operators in c# programming language to perform logical operations on defined operands based on our requirements.