Boolean logical operators - the boolean and, or, not, and xor operators - C# reference (2024)

  • Article

The logical Boolean operators perform logical operations with bool operands. The operators include the unary logical negation (!), binary logical AND (&), OR (|), and exclusive OR (^), and the binary conditional logical AND (&&) and OR (||).

  • Unary ! (logical negation) operator.
  • Binary , | (logical OR), and ^ (logical exclusive OR) operators. Those operators always evaluate both operands.
  • Binary and || (conditional logical OR) operators. Those operators evaluate the right-hand operand only if it's necessary.

For operands of the integral numeric types, the &, |, and ^ operators perform bitwise logical operations. For more information, see Bitwise and shift operators.

Logical negation operator !

The unary prefix ! operator computes logical negation of its operand. That is, it produces true, if the operand evaluates to false, and false, if the operand evaluates to true:

bool passed = false;Console.WriteLine(!passed); // output: TrueConsole.WriteLine(!true); // output: False

The unary postfix ! operator is the null-forgiving operator.

Logical AND operator &

The & operator computes the logical AND of its operands. The result of x & y is true if both x and y evaluate to true. Otherwise, the result is false.

The & operator always evaluates both operands. When the left-hand operand evaluates to false, the operation result is false regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the & operator is a method call, which is performed regardless of the value of the left-hand operand:

bool SecondOperand(){ Console.WriteLine("Second operand is evaluated."); return true;}bool a = false & SecondOperand();Console.WriteLine(a);// Output:// Second operand is evaluated.// Falsebool b = true & SecondOperand();Console.WriteLine(b);// Output:// Second operand is evaluated.// True

The conditional logical AND operator && also computes the logical AND of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to false.

For operands of the integral numeric types, the & operator computes the bitwise logical AND of its operands. The unary & operator is the address-of operator.

Logical exclusive OR operator ^

The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true. Otherwise, the result is false. That is, for the bool operands, the ^ operator computes the same result as the inequality operator !=.

Console.WriteLine(true ^ true); // output: FalseConsole.WriteLine(true ^ false); // output: TrueConsole.WriteLine(false ^ true); // output: TrueConsole.WriteLine(false ^ false); // output: False

For operands of the integral numeric types, the ^ operator computes the bitwise logical exclusive OR of its operands.

Logical OR operator |

The | operator computes the logical OR of its operands. The result of x | y is true if either x or y evaluates to true. Otherwise, the result is false.

The | operator always evaluates both operands. When the left-hand operand evaluates to true, the operation result is true regardless of the value of the right-hand operand. However, even then, the right-hand operand is evaluated.

In the following example, the right-hand operand of the | operator is a method call, which is performed regardless of the value of the left-hand operand:

bool SecondOperand(){ Console.WriteLine("Second operand is evaluated."); return true;}bool a = true | SecondOperand();Console.WriteLine(a);// Output:// Second operand is evaluated.// Truebool b = false | SecondOperand();Console.WriteLine(b);// Output:// Second operand is evaluated.// True

The conditional logical OR operator || also computes the logical OR of its operands, but doesn't evaluate the right-hand operand if the left-hand operand evaluates to true.

For operands of the integral numeric types, the | operator computes the bitwise logical OR of its operands.

Conditional logical AND operator &&

The conditional logical AND operator &&, also known as the "short-circuiting" logical AND operator, computes the logical AND of its operands. The result of x && y is true if both x and y evaluate to true. Otherwise, the result is false. If x evaluates to false, y isn't evaluated.

In the following example, the right-hand operand of the && operator is a method call, which isn't performed if the left-hand operand evaluates to false:

bool SecondOperand(){ Console.WriteLine("Second operand is evaluated."); return true;}bool a = false && SecondOperand();Console.WriteLine(a);// Output:// Falsebool b = true && SecondOperand();Console.WriteLine(b);// Output:// Second operand is evaluated.// True

The logical AND operator & also computes the logical AND of its operands, but always evaluates both operands.

Conditional logical OR operator ||

The conditional logical OR operator ||, also known as the "short-circuiting" logical OR operator, computes the logical OR of its operands. The result of x || y is true if either x or y evaluates to true. Otherwise, the result is false. If x evaluates to true, y isn't evaluated.

In the following example, the right-hand operand of the || operator is a method call, which isn't performed if the left-hand operand evaluates to true:

bool SecondOperand(){ Console.WriteLine("Second operand is evaluated."); return true;}bool a = true || SecondOperand();Console.WriteLine(a);// Output:// Truebool b = false || SecondOperand();Console.WriteLine(b);// Output:// Second operand is evaluated.// True

The logical OR operator | also computes the logical OR of its operands, but always evaluates both operands.

Nullable Boolean logical operators

For bool? operands, the and | (logical OR) operators support the three-valued logic as follows:

  • The & operator produces true only if both its operands evaluate to true. If either x or y evaluates to false, x & y produces false (even if another operand evaluates to null). Otherwise, the result of x & y is null.

  • The | operator produces false only if both its operands evaluate to false. If either x or y evaluates to true, x | y produces true (even if another operand evaluates to null). Otherwise, the result of x | y is null.

The following table presents that semantics:

xyx&yx|y
truetruetruetrue
truefalsefalsetrue
truenullnulltrue
falsetruefalsetrue
falsefalsefalsefalse
falsenullfalsenull
nulltruenulltrue
nullfalsefalsenull
nullnullnullnull

The behavior of those operators differs from the typical operator behavior with nullable value types. Typically, an operator that is defined for operands of a value type can be also used with operands of the corresponding nullable value type. Such an operator produces null if any of its operands evaluates to null. However, the & and | operators can produce non-null even if one of the operands evaluates to null. For more information about the operator behavior with nullable value types, see the Lifted operators section of the Nullable value types article.

You can also use the ! and ^ operators with bool? operands, as the following example shows:

bool? test = null;Display(!test); // output: nullDisplay(test ^ false); // output: nullDisplay(test ^ null); // output: nullDisplay(true ^ null); // output: nullvoid Display(bool? b) => Console.WriteLine(b is null ? "null" : b.Value.ToString());

The conditional logical operators && and || don't support bool? operands.

Compound assignment

For a binary operator op, a compound assignment expression of the form

x op= y

is equivalent to

x = x op y

except that x is only evaluated once.

The &, |, and ^ operators support compound assignment, as the following example shows:

bool test = true;test &= false;Console.WriteLine(test); // output: Falsetest |= true;Console.WriteLine(test); // output: Truetest ^= false;Console.WriteLine(test); // output: True

Note

The conditional logical operators && and || don't support compound assignment.

Operator precedence

The following list orders logical operators starting from the highest precedence to the lowest:

  • Logical negation operator !
  • Logical AND operator &
  • Logical exclusive OR operator ^
  • Logical OR operator |
  • Conditional logical AND operator &&
  • Conditional logical OR operator ||

Use parentheses, (), to change the order of evaluation imposed by operator precedence:

Console.WriteLine(true | true & false); // output: TrueConsole.WriteLine((true | true) & false); // output: Falsebool Operand(string name, bool value){ Console.WriteLine($"Operand {name} is evaluated."); return value;}var byDefaultPrecedence = Operand("A", true) || Operand("B", true) && Operand("C", false);Console.WriteLine(byDefaultPrecedence);// Output:// Operand A is evaluated.// Truevar changedOrder = (Operand("A", true) || Operand("B", true)) && Operand("C", false);Console.WriteLine(changedOrder);// Output:// Operand A is evaluated.// Operand C is evaluated.// False

For the complete list of C# operators ordered by precedence level, see the Operator precedence section of the C# operators article.

Operator overloadability

A user-defined type can overload the !, &, |, and ^ operators. When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. A user-defined type can't explicitly overload a compound assignment operator.

A user-defined type can't overload the conditional logical operators && and ||. However, if a user-defined type overloads the true and false operators and the & or | operator in a certain way, the && or || operation, respectively, can be evaluated for the operands of that type. For more information, see the User-defined conditional logical operators section of the C# language specification.

C# language specification

For more information, see the following sections of the C# language specification:

  • Logical negation operator
  • Logical operators
  • Conditional logical operators
  • Compound assignment

See also

  • C# operators and expressions
  • Bitwise and shift operators
Boolean logical operators - the boolean and, or, not, and xor operators - C# reference (2024)

FAQs

Is there an XOR operator in C#? ›

C# has the following logical operators: The & (and) operator returns true if both operands are true . The | (or) operator returns true if either operand is true . The ^ (xor) operator returns true if only one of its operands are true.

What is the difference between the or logical operator and the XOR logical operator? ›

Now the OR operator is saying, if the first argument or the second argument are true, then the result is true. Lastly, the XOR (exclusive OR) operator is saying, if either input is true, then the result is true, but if both inputs are true, then the result is false.

What is the Boolean XOR in C? ›

The XOR (^) Logical Operator In C

The XOR operation evaluates to true (1) if the operands have opposite truth values (one operand is true and the other is false) and false (0) if the operands have the same truth value (both true or both false).

How to use Boolean operators in C#? ›

C# allows us to create a compound boolean expression using the logical AND operator, && . The operator takes two operands, and the resulting expression is True if both operands are True individually. If either operand is False , the overall expression is False .

How do you write XOR in Boolean? ›

The logic symbols ⊕, Jpq, and ⊻ can be used to denote an XOR operation in algebraic expressions. C-like languages use the caret symbol ^ to denote bitwise XOR. (Note that the caret does not denote logical conjunction (AND) in these languages, despite the similarity of symbol.)

What is an example of a XOR operator? ›

For example, 5 Xor 3 is 6. To see why this is so, convert 5 and 3 to their binary representations, 101 and 011. Then use the previous table to determine that 101 Xor 011 is 110, which is the binary representation of the decimal number 6.

Are logical operators the same as Boolean? ›

Logical or Boolean operators are often used when you need to evaluate multiple relational expressions to return a single value. For example, in a Selection block, an action may depend on the evaluation of more than one expression. The three primitive (basic) logical operators are AND, OR, and NOT.

What are the three main logical operators? ›

There are three logical operators: and , or , and not . The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 and x < 10 is true only if x is greater than 0 and at the same time, x is less than 10.

What are 5 common Boolean searches? ›

Boolean operators are specific words and symbols that you can use to expand or narrow your search parameters when using a database or search engine. The most common Boolean operators are AND, OR, NOT or AND NOT, quotation marks “”, parentheses (), and asterisks *.

How does the XOR operator work in C? ›

The bitwise XOR (exclusive or) performs an exclusive disjunction, which is equivalent to adding two bits and discarding the carry. The result is zero only when we have two zeroes or two ones. XOR can be used to toggle the bits between 1 and 0. Thus i = i ^ 1 when used in a loop toggles its values between 1 and 0.

What are the Boolean logic operators in C? ›

The logical operators evaluate the logical expression and return a result. The result is always a Boolean value. A Boolean value determines whether the expression is true or false . There are three logical operators in C programming: logical AND( && ), logical OR( || ), and logical NOT ( ! ).

What is the opposite of XOR in Boolean? ›

The inverse of XOR is XOR itself. Hopefully, this helps. Inverse of a XOR is XOR itself.

What is the logical XOR operator in C#? ›

Logical XOR Operator (^)

If both are the same, it returns false. This operator is particularly useful when you want to ensure that exactly one of two conditions is true, but not both. Since the values of hasPassword and hasSmartCard are different, the logical XOR returns true.

What is the difference between boolean and boolean in C#? ›

In C#, Boolean is a system-provided struct, while bool is an alias for Boolean . They are technically the same; however, bool is more widely used due to its brevity. Both isAlive and isDead hold boolean values, but the latter looks cleaner and is more appreciated in the C# community.

How to define a boolean in C#? ›

C# declaration of a bool variable.

In C#, we use the keyword “bool” followed by the variable name to declare a Boolean variable.

Is there a XOR operator in C? ›

Bitwise XOR (^) operator will take two equal length binary sequence and perform bitwise XOR operation on each pair of bit sequence. XOR operator will return 1, if both bits are different. If bits are same, it will return 0.

How to create XOR on dotnet? ›

In C#.Net the logical boolean operators have boolean operands and produce a boolean result. The caret symbol ^ is used as the exclusive or (XOR) operator, these logical operators allow us to combine multiple boolean expressions to form a more complex boolean expression.

What is the XOR equation in C? ›

The ^ (bitwise XOR) in C takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C takes two numbers, the left shifts the bits of the first operand, and the second operand decides the number of places to shift.

How to swap using XOR in C? ›

The XOR Swap Algorithm

The new value of a is a combination of both original values. *b = *a ^ *b; Now, we use the encrypted value of a (from step 1) and perform an XOR with the original value of b . This operation extracts the value of a and assigns it to b .

Top Articles
¿Cómo calcular el costo de una pizza? Costeo de menú
Respuestas del examen de certificación de Campañas de Búsqueda de Google Ads
Chren, inaugural chair of the Department of Dermatology, to step down
scotty rasmussen paternity court
Savory Dishes Made Simple: 6 Ingredients to Kick Up the Flavor - MSGdish
Indio Mall Eye Doctor
North Carolina Houses For Rent Craigslist
Circle L Bassets
Uber Hertz Marietta
Adventhealth Employee Hub Login
Ecolab Mppa Charges
Thomas Funeral Home Sparta Nc
For My Derelict Favorite Novel Online
1977 Elo Hit Wsj Crossword
What Does Fox Stand For In Fox News
Craiglist Tulsa Ok
Lynette Mettey Feet
NEU: LEAKSHIELD - das sicherste Flüssigkeits-Kühlsystem der Welt - Wasserkühlung
Nancy Pazelt Obituary
Skip The Games Lawton Oklahoma
Rufus Rhett Bosarge
Anon Rotten Tomatoes
Lieu Gia Trang Houston Texas
Camwhor*s Bypass 2022
2013 Freightliner Cascadia Fuse Box Diagram
Urbfsdreamgirl
Twitter Jeff Grubb
AC Filters | All About Air Filters for AC | HVAC Filters
Heyimbee Forum
Walgreens On Nacogdoches And O'connor
2014 Chevy Malibu Belt Diagram
Courtney Lynn Playboy
Denise Frazier Leak
Circuit Court Peoria Il
Horoscope Daily Yahoo
Dutchessravenna N Word
MyChart | University Hospitals
Dpsmypepsico
Pulaski County Busted Newspaper
18006548818
GW2 Fractured update patch notes 26th Nov 2013
Ohio State Football Wiki
Alylynn
What Is TAA Trade Agreements Act Compliance Trade Agreement Act Certification
Inter Miami Vs Fc Dallas Total Sportek
Mybrownhanky Com
Kieaira.boo
Craigslist.com Hawaii
Hughie Francis Foley
Keystyle.hensel Phelps.com/Account/Login
Timothy Warren Cobb Obituary
Stuckey Furniture
Latest Posts
Article information

Author: Nathanael Baumbach

Last Updated:

Views: 5516

Rating: 4.4 / 5 (75 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Nathanael Baumbach

Birthday: 1998-12-02

Address: Apt. 829 751 Glover View, West Orlando, IN 22436

Phone: +901025288581

Job: Internal IT Coordinator

Hobby: Gunsmithing, Motor sports, Flying, Skiing, Hooping, Lego building, Ice skating

Introduction: My name is Nathanael Baumbach, I am a fantastic, nice, victorious, brave, healthy, cute, glorious person who loves writing and wants to share my knowledge and understanding with you.