Home Basics C# Logical Operators

C# Logical Operators

The operands in logical operators must always contain only Boolean values. Otherwise, Logical Operators will throw an error.

Logical operators are used in decision making and loops.

This is a list of the logical operators

Expression Read Explanation
a&&b a and b && operates on boolean operands only. It evaluates its first operand. If the result is false, it returns false. Otherwise, it evaluates and returns the results of the second operand. Note that, if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical conjunction performed by the & operator. This is an example of Short Circuit Evaluation.
a || b a or b || operates on boolean operands only. It evaluates the first operand. If the result is true, it returns true. Otherwise, it evaluates and returns the results of the second operand. Note that, if evaluating the second operand would hypothetically have no side effects, the results are identical to the logical disjunction performed by the | operator. This is an example of Short Circuit Evaluation.
!a not a ! operates on a boolean operand only. It evaluates its operand and returns the negation (“NOT”) of the result. That is, it returns true if a evaluates to false and it returns false if a evaluates to true.

 

Table of Contents

AND

Operand1 Operand2 AND
true true true
true false false
false true false
false false false

OR

Operand1 Operand2 OR
true true true
true false true
false true true
false false false

NOT

Operand NOT
true false
false true

 

Example

 

using System;

public class Program
{
	public static void Main()
	{
		bool result;
		bool a = true;
		int firstNumber = 15, secondNumber = 30;

		// OR operator
		result = (firstNumber == secondNumber) || (firstNumber > 5);
		Console.WriteLine(result);

		// AND operator
		result = (firstNumber == secondNumber) && (firstNumber > 5);
		Console.WriteLine(result);
		
		// NOT operator
		result = !a;
		Console.WriteLine(result);		
	}
}

You should see the following

True
False
False

You may also like