This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Boolean logical operators - AND, OR, NOT, XOR

  • 5 contributors

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 AND) , | (logical OR) , and ^ (logical exclusive OR) operators. Those operators always evaluate both operands.
  • Binary && (conditional logical AND) 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 :

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:

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 != .

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:

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 :

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 :

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 & (logical AND) 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:

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:

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

  • Compound assignment

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

is equivalent to

except that x is only evaluated once.

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

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:

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

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
  • C# operators and expressions
  • Bitwise and shift operators

Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see: https://aka.ms/ContentUserFeedback .

Submit and view feedback for

Additional resources

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

boolean-logical-operators.md

Latest commit, file metadata and controls, boolean logical operators - and, or, not, xor.

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 AND) , | (logical OR) , and ^ (logical exclusive OR) operators. Those operators always evaluate both operands.
  • Binary && (conditional logical AND) 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 :

[!code-csharp-interactive logical negation ]

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:

[!code-csharp-interactive logical AND ]

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 != .

[!code-csharp-interactive logical exclusive OR ]

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:

[!code-csharp-interactive logical OR ]

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 :

[!code-csharp-interactive conditional logical AND ]

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 :

[!code-csharp-interactive conditional logical OR ]

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 & (logical AND) 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:

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:

[!code-csharp-interactive lifted negation and xor ]

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

  • Compound assignment

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

is equivalent to

except that x is only evaluated once.

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

[!code-csharp-interactive compound assignment ]

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:

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

[!code-csharp-interactive operator precedence ]

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
  • C# operators and expressions
  • Bitwise and shift operators

The parenthesized condition of the if statement is a Boolean expression . In Listing 4.29 , the condition is highlighted.

Boolean expressions appear within many control flow statements. Their key characteristic is that they always evaluate to true or false . For input < 9 to be allowed as a Boolean expression, it must result in a bool . The compiler disallows x = 42 , for example, because this expression assigns x and results in the value that was assigned instead of checking whether the value of the variable is 42 .

C# eliminates a coding error commonly found in C and C++. In C++, Listing 4.30 is allowed.

Although at first glance this code appears to check whether input equals 9 , Chapter 1 showed that = represents the assignment operator, not a check for equality. The return from the assignment operator is the value assigned to the variable—in this case, 9 . However, 9 is an int , so it does not qualify as a Boolean expression and is not allowed by the C# compiler. The C and C++ languages treat integers that are nonzero as true and integers that are zero as false . C#, by contrast, requires that the condition actually be of a Boolean type; integers are not allowed.

Relational and equality operators determine whether a value is greater than, less than, or equal to another value. Table 4.2 lists all the relational and equality operators. All are binary operators.

The C# syntax for equality uses == , just as many other programming languages do. For example, to determine whether input equals 9 , you use input == 9 . The equality operator uses two equal signs to distinguish it from the assignment operator, = . The exclamation point signifies NOT in C#, so to test for inequality you use the inequality operator, != .

Relational and equality operators always produce a bool value, as shown in Listing 4.31 .

In the full tic-tac-toe program listing, you use the equality operator to determine whether a user has quit. The Boolean expression in Listing 4.32 includes an OR ( || ) logical operator, which the next section discusses in detail.

The logical operators have Boolean operands and produce a Boolean result. Logical operators allow you to combine multiple Boolean expressions to form more complex Boolean expressions. The logical operators are | , || , & , && , and ^ , corresponding to OR, AND, and exclusive OR. The | and & versions of OR and AND are rarely used for Boolean logic, for reasons which we discuss in this section.

In Listing 4.32 , if the user enters quit or presses the Enter key without typing in a value, it is assumed that they want to exit the program. To enable two ways for the user to resign, you can use the logical OR operator, || . The || operator evaluates Boolean expressions and results in a true value if either operand is true (see Listing 4.33 ).

It is not necessary to evaluate both sides of an OR expression, because if one operand is true , the result is known to be true regardless of the value of the other operand. Like all operators in C#, the left operand is evaluated before the right one, so if the left portion of the expression evaluates to true , the right portion is ignored. In the example in Listing 4.33 , if hourOfTheDay has the value 33 , then (hourOfTheDay > 23) evaluates to true and the OR operator ignores the second half of the expression, short-circuiting it. Short-circuiting an expression also occurs with the Boolean AND operator. (Note that the parentheses are not necessary here; the logical operators are of lower precedence than the relational operators. However, it is clearer to the novice reader when the subexpressions are parenthesized for clarity.)

The Boolean AND operator, && , evaluates to true only if both operands evaluate to true . If either operand is false , the result will be false . Listing 4.34 writes a message if the given variable is both greater than 10 and less than 24. 3 Similarly to the OR operator, the AND operator will not always evaluate the right side of the expression. If the left operand is determined to be false , the overall result will be false regardless of the value of the right operand, so the runtime skips evaluating the right operand.

The caret symbol, ^ , is the exclusive OR (XOR) operator. When applied to two Boolean operands, the XOR operator returns true only if exactly one of the operands is true, as shown in Table 4.3 .

Unlike the Boolean AND and Boolean OR operators, the Boolean XOR operator does not short-circuit: It always checks both operands, because the result cannot be determined unless the values of both operands are known. Note that the XOR operator is exactly the same as the Boolean inequality operator.

The logical negation operator , or NOT operator , ! , inverts a bool value. This operator is a unary operator, meaning it requires only one operand. Listing 4.35 demonstrates how it works, and Output 4.16 shows the result.

At the beginning of Listing 4.35 , valid is set to false . You then use the negation operator on valid and assign the value to result .

As an alternative to using an if - else statement to select one of two values, you can use the conditional operator . The conditional operator uses both a question mark and a colon; the general format is as follows:

condition ? consequent : alternative

The conditional operator is a ternary operator because it has three operands: condition , consequent , and alternative . (As it is the only ternary operator in C#, it is often called the ternary operator , but it is clearer to refer to it by its name than by the number of operands it takes.) Like the logical operators, the conditional operator uses a form of short-circuiting. If the condition operator evaluates to true , the conditional operator evaluates only consequent . If the conditional evaluates to false , it evaluates only alternative . The result of the operator is the evaluated expression.

Listing 4.36 illustrates the use of the conditional operator. The full listing of this program appears in of the source code.

The program swaps the current player. To do so, it checks whether the current value is 2 . This is the conditional portion of the conditional expression. If the result of the condition is true , the conditional operator results in the consequent value, 1 . Otherwise, it results in the alternative value, 2 . Unlike in an if statement, the result of the conditional operator must be assigned (or passed as a parameter); it cannot appear as an entire statement on its own.

Prior to C# 9.0, the language required that the output (the consequent and alternative) expressions in a conditional operator be consistently typed and that the consistent type be determined without examination of the surrounding context of the expression, including the resulting type assigned. However, C# 9.0 added support for target-typed conditional expressions so that even if the consequent and alternative expressions are of different types (such as string and int ) and neither is convertible to the other, the statement is still allowed if both types will implicitly cast to the targeted type. For example, even if you have object result = condition ? "abc" : 123; , the C# compiler will allow it because both the potential conditional output types will implicitly cast to object .

________________________________________

  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key) && !currentPage.some(p => p.level > item.level), }" :href="item.href"> Introduction
  • p.key == item.key) && !currentPage.some(p => p.level > item.level), }" > p.key == item.key), }" :href="item.href"> {{item.title}}
  • PyQt5 ebook
  • Tkinter ebook
  • SQLite Python
  • wxPython ebook
  • Windows API ebook
  • Java Swing ebook
  • Java games ebook
  • MySQL Java ebook

C# operator

last modified July 5, 2023

In this article we cover C# operators.

Expressions are constructed from operands and operators. The operators of an expression indicate which operations to apply to the operands. The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

An operator is a special symbol which indicates a certain process is carried out. Operators in programming languages are taken from mathematics. Programmers work with data. The operators are used to process data. An operand is one of the inputs (arguments) of an operator.

C# operator list

The following table shows a set of operators used in the C# language.

An operator usually has one or two operands. Those operators that work with only one operand are called unary operators . Those who work with two operands are called binary operators . There is also one ternary operator ?: , which works with three operands.

Certain operators may be used in different contexts. For example the + operator. From the above table we can see that it is used in different cases. It adds numbers, concatenates strings or delegates; indicates the sign of a number. We say that the operator is overloaded .

C# unary operators

C# unary operators include: +, -, ++, --, cast operator (), and negation !.

C# sign operators

There are two sign operators: + and - . They are used to indicate or change the sign of a value.

The + and - signs indicate the sign of a value. The plus sign can be used to indicate that we have a positive number. It can be omitted and it is mostly done so.

The minus sign changes the sign of a value.

C# increment and decrement operators

Incrementing or decrementing a value by one is a common task in programming. C# has two convenient operators for this: ++ and -- .

The above two pairs of expressions do the same.

In the above example, we demonstrate the usage of both operators.

We initiate the x variable to 6. Then we increment x two times. Now the variable equals to 8.

We use the decrement operator. Now the variable equals to 7.

C# explicit cast operator

The explicit cast operator () can be used to cast a type to another type. Note that this operator works only on certain types.

In the example, we explicitly cast a float type to int .

Negation operator

The negation operator (!) reverses the meaning of its operand.

In the example, we build a negative condition: it is executed if the inverse of the expression is valid.

C# assignment operator

The assignment operator = assigns a value to a variable. A variable is a placeholder for a value. In mathematics, the = operator has a different meaning. In an equation, the = operator is an equality operator. The left side of the equation is equal to the right one.

Here we assign a number to the x variable.

The previous expression does not make sense in mathematics. But it is legal in programming. The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x .

This code example results in syntax error. We cannot assign a value to a literal.

C# concatenating strings

The + operator is also used to concatenate strings.

We join three strings together using string concatenation operator.

C# arithmetic operators

The following is a table of arithmetic operators in C#.

The following example shows arithmetic operations.

In the preceding example, we use addition, subtraction, multiplication, division, and remainder operations. This is all familiar from the mathematics.

The % operator is called the remainder or the modulo operator. It finds the remainder of division of one number by another. For example, 9 % 4 , 9 modulo 4 is 1, because 4 goes into 9 twice with a remainder of 1.

Next we show the distinction between integer and floating point division.

In the preceding example, we divide two numbers.

In this code, we have done integer division. The returned value of the division operation is an integer. When we divide two integers the result is an integer.

If one of the values is a double or a float, we perform a floating point division. In our case, the second operand is a double so the result is a double.

C# Boolean operators

In C#, we have three logical operators. The bool keyword is used to declare a Boolean value.

Boolean operators are also called logical.

Many expressions result in a boolean value. Boolean values are used in conditional statements.

Relational operators always result in a boolean value. These two lines print false and true.

The body of the if statement is executed only if the condition inside the parentheses is met. The y > x returns true, so the message "y is greater than x" is printed to the terminal.

The true and false keywords represent boolean literals in C#.

Example shows the logical and operator. It evaluates to true only if both operands are true.

Only one expression results in True .

The logical or || operator evaluates to true, if either of the operands is true.

If one of the sides of the operator is true, the outcome of the operation is true.

Three of four expressions result in true.

The negation operator ! makes true false and false true.

The example shows the negation operator in action.

The || , and && operators are short circuit evaluated. Short circuit evaluation means that the second argument is only evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of the logical and evaluates to false, the overall value must be false; and when the first argument of logical or evaluates to true, the overall value must be true. Short circuit evaluation is used mainly to improve performance.

An example may clarify this a bit more.

We have two methods in the example. They are used as operands in boolean expressions.

The One method returns false . The short circuit && does not evaluate the second method. It is not necessary. Once an operand is false , the result of the logical conclusion is always false . Only "Inside one" is only printed to the console.

In the second case, we use the || operator and use the Two method as the first operand. In this case, "Inside two" and "Pass" strings are printed to the terminal. It is again not necessary to evaluate the second operand, since once the first operand evaluates to true , the logical or is always true .

C# relational operators

Relational operators are used to compare values. These operators always result in boolean value.

Relational operators are also called comparison operators.

In the code example, we have four expressions. These expressions compare integer values. The result of each of the expressions is either true or false. In C# we use == to compare numbers. Some languages like Ada, Visual Basic, or Pascal use = for comparing numbers.

C# bitwise operators

Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal, decimal, or hexadecimal symbols are only notations of the same number. Bitwise operators work with bits of a binary number. Bitwise operators are seldom used in higher level languages like C#.

The bitwise negation operator changes each 1 to 0 and 0 to 1.

The operator reverts all bits of a number 7. One of the bits also determines, whether the number is negative or not. If we negate all the bits one more time, we get number 7 again.

The bitwise and operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 only if both corresponding bits in the operands are 1.

The first number is a binary notation of 6, the second is 3, and the result is 2.

The bitwise or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if either of the corresponding bits in the operands is 1.

The result is 00110 or decimal 7.

The bitwise exclusive or operator performs bit-by-bit comparison between two numbers. The result for a bit position is 1 if one or the other (but not both) of the corresponding bits in the operands is 1.

The result is 00101 or decimal 5.

C# compound assignment operators

The compound assignment operators consist of two operators. They are shorthand operators.

The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable.

Other compound operators are:

In the example, we use two compound operators.

The a variable is initiated to one. 1 is added to the variable using the non-shorthand notation.

Using a += compound operator, we add 5 to the a variable. The statement is equal to a = a + 5; .

Using the *= operator, the a is multiplied by 3. The statement is equal to a = a * 3; .

C# new operator

The new operator is used to create objects and invoke constructors.

In the example, we create a new custom object and a array of integers utilizing the new operator.

This is a constructor. It is called at the time of the object creation.

C# access operator

The access operator [] is used with arrays, indexers, and attributes.

In the example, we use the [] operator to get an element of an array, value of a dictionary pair, and activate a built-in attribute.

We define an array of integers. We get the first element with vals[0] .

A dictionary is created. With domains["de"] , we get the value of the pair that has the "de" key.

We active the built-in Obsolete attribute. The attribute issues a warning.

When we run the program, it produces the warning: warning CS0618: 'oldMethod()' is obsolete: 'Don't use OldMethod, use NewMethod instead' .

C# index from end operator ^

The index from end operator ^ indicates the element position from the end of a sequence. For instance, ^1 points to the last element of a sequence and ^n points to the element with offset length - n .

In the example, we apply the operator on an array and a string.

We print the last and the last but one element of the array.

We print the last letter of the word.

C# range operator ..

The .. operator specifies the start and end of a range of indices as its operands. The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range.

Operands of the .. operator can be omitted to get an open-ended range.

In the example, we use the .. operator to get array slices.

We create an array slice from index 1 till index 4; the last index 4 is not included.

Here we esentially create a copy of the array.

C# type information

Now we concern ourselves with operators that work with types.

The sizeof operator is used to obtain the size in bytes for a value type. The typeof is used to obtain the System.Type object for a type.

We use the sizeof and typeof operators.

We can see that the int type is an alias for System.Int32 and the float is an alias for the System.Single type.

The is operator checks if an object is compatible with a given type.

We create two objects from user defined types.

We have a Base and a Derived class. The Derived class inherits from the Base class.

Base equals Base and so the first line prints True. The Base is also compatible with Object type. This is because each class inherits from the mother of all classes — the Object class.

The derived object is compatible with the Base class because it explicitly inherits from the Base class. On the other hand, the _base object has nothing to do with the Derived class.

The as operator is used to perform conversions between compatible reference types. When the conversion is not possible, the operator returns null. Unlike the cast operation which raises an exception.

In the above example, we use the as operator to perform casting.

We try to cast various types to the string type. But only once the casting is valid.

C# operator precedence

The operator precedence tells us which operators are evaluated first. The precedence level is necessary to avoid ambiguity in expressions.

What is the outcome of the following expression, 28 or 40?

Like in mathematics, the multiplication operator has a higher precedence than addition operator. So the outcome is 28.

To change the order of evaluation, we can use parentheses. Expressions inside parentheses are always evaluated first.

The following table shows common C# operators ordered by precedence (highest precedence first):

Operators on the same row of the table have the same precedence.

In this code example, we show a few expressions. The outcome of each expression is dependent on the precedence level.

This line prints 28. The multiplication operator has a higher precedence than addition. First, the product of 5*5 is calculated, then 3 is added.

In this case, the negation operator has a higher precedence. First, the first true value is negated to false, then the | operator combines false and true, which gives true in the end.

C# associativity rule

Sometimes the precedence is not satisfactory to determine the outcome of an expression. There is another rule called associativity . The associativity of operators determines the order of evaluation of operators with the same precedence level.

What is the outcome of this expression, 9 or 1? The multiplication, deletion and the modulo operator are left to right associated. So the expression is evaluated this way: (9 / 3) * 3 and the result is 9.

Arithmetic, boolean, relational, and bitwise operators are all left to right associated.

On the other hand, the assignment operator is right associated.

In the example, we have two cases where the associativity rule determines the expression.

The assignment operator is right to left associated. If the associativity was left to right, the previous expression would not be possible.

The compound assignment operators are right to left associated. We might expect the result to be 1. But the actual result is 0. Because of the associativity. The expression on the right is evaluated first and than the compound assignment operator is applied.

C# null-conditional operator

A null-conditional operator applies a member access, ?. , or element access, ?[] , operation to its operand only if that operand evaluates to non-null. If the operand evaluates to null , the result of applying the operator is null.

In the example, we have a User class with two members: Name and Occupation . We access the name member of the objects with the help of the ?. operator.

We have a list of users. One of them is initialized with null values.

We use the ?. to access the Name member and call the ToUpper method. The ?. prevents the System.NullReferenceException by not calling the ToUpper on the null value.

In the following example, we use the ?[] operator. The operator allows to place null values into a collection.

In this example, we have a null value in an array. We prevent the System.NullReferenceException by applying the ?. operator on the array elements.

C# null-coalescing operator

The null-coalescing operator ?? is used to define a default value for a nullable type. It returns the left-hand operand if it is not null; otherwise it returns the right operand. When we work with databases, we often deal with absent values. These values come as nulls to the program. This operator is a convenient way to deal with such situations.

An example program for null-coalescing operator.

Two nullable int types are initiated to null . The int? is a shorthand for Nullable<int> . It allows to have null values assigned to int types.

We want to assign a value to z variable. But it must not be null . This is our requirement. We can easily use the null-coalescing operator for that. In case both x and y variables are null, we assign -1 to z .

C# null-coalescing assignment operator

The null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null . The ??= operator does not evaluate its right-hand operand if the left-hand operand evaluates to non-null. It is available in C# 8.0 and later.

In the example, we use the null-coalescing assignment operator on a list of integer values.

First, the list is assigned to null .

We use the ??= to assign a new list object to the variable. Since it is null , the list is assigned.

We add some values to the list and print its contents.

We try to assign a new list object to the variable. Since the variable is not null anymore, the list is not assigned.

C# ternary operator

The ternary operator ?: is a conditional operator. It is a convenient operator for cases where we want to pick up one of two values, depending on the conditional expression.

If cond-exp is true, exp1 is evaluated and the result is returned. If the cond-exp is false, exp2 is evaluated and its result is returned.

In most countries the adulthood is based on your age. You are adult if you are older than a certain age. This is a situation for a ternary operator.

First the expression on the right side of the assignment operator is evaluated. The first phase of the ternary operator is the condition expression evaluation. So if the age is greater or equal to 18, the value following the ? character is returned. If not, the value following the : character is returned. The returned value is then assigned to the adult variable.

A 31 years old person is adult.

C# Lambda operator

The => token is called the lambda operator. It is an operator taken from functional languages. This operator can make the code shorter and cleaner. On the other hand, understanding the syntax may be tricky. Especially if a programmer never used a functional language before.

Wherever we can use a delegate, we also can use a lambda expression. A definition for a lambda expression is: a lambda expression is an anonymous function that can contain expressions and statements. On the left side we have a group of data and on the right side an expression or a block of statements. These statements are applied on each item of the data.

In lambda expressions we do not have a return keyword. The last statement is automatically returned. And we do not need to specify types for our parameters. The compiler will guess the correct parameter type. This is called type inference.

We have a list of integer numbers. We print all numbers that are greater than 3.

We have a generic list of integers.

Here we use the lambda operator. The FindAll method takes a predicate as a parameter. A predicate is a special kind of a delegate that returns a boolean value. The predicate is applied for all items of the list. The val is an input parameter specified without a type. We could explicitly specify the type but it is not necessary.

The compiler will expect an int type. The val is a current input value from the list. It is compared if it is greater than 3 and a boolean true or false is returned. Finally, the FindAll will return all values that met the condition. They are assigned to the sublist collection.

The items of the sublist collection are printed to the terminal.

Values from the list of integers that are greater than 3.

This is the same example. We use a anonymous delegate instead of a lambda expression.

C# calculating prime numbers

We are going to calculate prime numbers.

In the above example, we deal with many various operators. A prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. We pick up a number and divide it by numbers, from 1 up to the picked up number. Actually, we do not have to try all smaller numbers; we can divide by numbers up to the square root of the chosen number. The formula will work. We use the remainder division operator.

We calculate primes from these numbers.

By definition, 1 is not a prime

We skip the calculations for 2 and 3: they are primes. Note the usage of the equality and conditional or operators. The == has a higher precedence than the || operator. So we do not need to use parentheses.

We are OK if we only try numbers smaller than the square root of a number in question. It was mathematically proven that it is sufficient to take into account values up to the square root of the number in question.

This is a while loop. The i is the calculated square root of the number. We use the decrement operator to decrease the i by one each loop cycle. When the i is smaller than 1, we terminate the loop. For example, we have number 9. The square root of 9 is 3. We divide the 9 number by 3 and 2.

This is the core of the algorithm. If the remainder division operator returns 0 for any of the i values then the number in question is not a prime.

C# operators and expressions

In this article we covered C# operators.

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials .

c# boolean assignment operators

C# Operators

Operators in C# are some special symbols that perform some action on operands. In mathematics, the plus symbol (+) do the sum of the left and right numbers. In the same way, C# includes various operators for different types of operations.

The following example demonstrates the + operator in C#.

In the above example, + operator adds two number literals and assign the result to a variable. It also adds the values of two int variables and assigns the result to a variable.

Some operators behave differently based on the type of the operands. For example, + operator concatenates two strings.

C# includes the following categories of operators:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Equality operators
  • Boolean logical operators
  • Betwise and shift operators
  • Member access operators
  • Type-cast operators
  • Pointer related operators

Arithmetic Operators

The arithmetic operators perform arithmetic operations on all the numeric type operands such as sbyte, byte, short, ushort, int, uint, long, ulong, float, double, and decimal.

Assignment Operators

The assignment operator = assigns its right had value to its left-hand variable, property, or indexer. It can also be used with other arithmetic, Boolean logical, and bitwise operators.

Comparison Operators

Comparison operators compre two numeric operands and returns true or false.

Equality Operators

The equality operator checks whether the two operands are equal or not.

Boolean Logical Operators

The Boolean logical operators perform a logical operation on bool operands.

Operator Evaluation & Precedence

Evaluation of the operands in an expression starts from left to right. If multiple operators are used in an expression, then the operators with higher priority are evaluated before the operators with lower priority.

The following table lists operators starting with the higher precedence operators to lower precedence operators.

The following example demonstrates operator precedence:

Learn about C# operators in details .

  • Difference between Array and ArrayList
  • Difference between Hashtable and Dictionary
  • How to write file using StreamWriter in C#?
  • How to sort the generic SortedList in the descending order?
  • Difference between delegates and events in C#
  • How to read file using StreamReader in C#?
  • How to calculate the code execution time in C#?
  • Design Principle vs Design Pattern
  • How to convert string to int in C#?
  • Boxing and Unboxing in C#
  • More C# articles

c# boolean assignment operators

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

  • C# Questions & Answers
  • C# Skill Test
  • C# Latest Articles

C Sharp Operators and Expressions

In C# Variables and Constants we looked at using variables and constants in C# and also described the different variable and constant types. Being able to create constants and variables is only part of the story however. The next step is to learn how to use these variables and constants in C# code. The primary method for working with the data stored in constants and variables is in the form of expressions . In this chapter we will look in detail at C# expressions and operators.

What is an Expression?

The most basic expression consists of an operator , two operands and an assignment . The following is an example of an expression:

In the above example the (+) operator is used to add two operands (1 and 2) together. The assignment operator (=) subsequently assigns the result of the addition to an integer variable named theResult . The operands could just have easily been variables or constants (or a mixture of each) instead of the actual numerical values used in the example.

In the remainder of this chapter we will look at the various types of operators available in C#.

The Basic Assignment Operator

We have already looked at the most basic of assignment operators, the = operator. This assignment operator simply assigns the result of an expression to a variable. In essence the = assignment operator takes two operands. The left hand operand is the variable to which a value is to be assigned and the right hand operand is the value to be assigned. The right hand operand is, more often than not, an expression which performs some type of arithmetic or logical evaluation. The following examples are all valid uses of the assignment operator:

Assignment operators may also be chained to assign the same value to multiple variables. For example, the following code example assigns the value 20 to the x, y and z variables:

C# Arithmetic Operators

C# provides a range of operators for the purpose of creating mathematical expressions. These operators primarily fall into the category of binary operators in that they take two operands. The exception is the unary negative operator (-) which serves to indicate that a value is negative rather than positive. This contrasts with the subtraction operator (-) which takes two operands (i.e. one value to be subtracted from another). For example:

Note that multiple operators may be used in a single expression.

For example:

Whilst the above code is perfectly valid it is important to be aware that C# does not evaluate the expression from left to right or right to left, but rather in an order specified by the precedence of the various operators. Operator precedence is an important topic to understand since it impacts the result of a calculation and will be covered in detail the next section.

C# Operator Precedence

When humans evaluate expressions, they usually do so starting at the left of the expression and working towards the right. For example, working from left to right we get a result of 300 from the following expression:

10 + 20 * 10 = 300

This is because we, as humans, add 10 to 20, resulting in 30 and then multiply that by 10 to arrive at 300. Ask C# to perform the same calculation and you get a very different answer:

The above code, when compiled and executed, will output the result 210.

This is a direct result of operator precedence . C# has a set of rules that tell it in which order operators should be evaluated in an expression. Clearly, C# considers the multiplication operator (*) to be of a higher precedence than the addition (+) operator.

Fortunately the precedence built into C# can be overridden by surrounding the lower priority section of an expression with parentheses. For example:

In the above example, the expression fragment enclosed in parentheses is evaluated before the higher precedence multiplication resulting in a value of 300.

The following table outlines the C# operator precedence order from highest precedence to lowest:

Compound Assignment Operators

C# provides a number of operators designed to combine an assignment with a mathematical or logical operation. These are primarily of use when performing an evaluation where the result is to be stored in one of the operands. For example, one might write an expression as follows:

The above expression adds the value contained in variable x to the value contained in variable y and stores the result in variable x. This can be simplified using the addition compound assignment operator:

The above expression performs exactly the same task as x = x + y but saves the programmer some typing. This is yet another feature that C# has inherited from the C programming language.

Numerous compound assignment operators are available in C#. The most frequently used are outlined in the following table:

Increment and Decrement Operators

Another useful shortcut can be achieved using the C# increment and decrement operators. As with the compound assignment operators described in the previous section, consider the following C# code fragment:

These expressions increment and decrement the value of x by 1. Instead of using this approach it is quicker to use the ++ and -- operators. The following examples perform exactly the same tasks as the examples above:

These operators can be placed either before or after the variable name. If the operator is placed before the variable name the increment or decrement is performed before any other operations are performed on the variable. For example, in the following example, x is incremented before it is assigned to y, leaving y with a value of 10:

In the following example, the value of x (9) is assigned to variable y before the decrement is performed. After the expression is evaluated the value of y will be 9 and the value of x will be 8.

Comparison Operators

In addition to mathematical and assignment operators, C# also includes set of logical operators useful for performing comparisons. These operators all return a Boolean ( bool ) true or false result depending on the result of the comparison. These operators are binary in that they work with two operands.

Comparison operators are most frequently used in constructing program flow control. For example an if statement may be constructed based on whether one value matches another:

The result of a comparison may also be stored in a bool variable. For example, the following code will result in a true value being stored in the variable result:

Clearly 10 is less than 20, resulting in a true evaluation of the x < y expression. The following table lists the full set of C# comparison operators:

Boolean Logical Operators

Another set of operators which return boolean true and false values are the C# boolean logical operators . These operators both return boolean results and take boolean values as operands. The key operators are NOT (!), AND (&&), OR (||) and XOR (^).

The NOT (!) operator simply inverts the current value of a boolean variable, or the result of an expression. For example, if a variable named flag is currently true , prefixing the variable with a '!' character will invert the value to be false :

The OR (||) operator returns true if one of its two operands evaluates to true , otherwise it returns false. For example, the following example evaluates to true because at least one of the expressions either side of the OR operator is true:

The AND (&&) operator returns true only if both operands evaluate to be true. The following example will return false because only one of the two operand expressions evaluates to true :

The XOR (^) operator returns true if one and only one of the two operands evaluates to true. For example, the following example will return true since only one operator evaluates to be true:

If both operands evaluated to be true, or both were false the expression with return false.

The Ternary Operator

C# uses something called a ternary operator to provide a shortcut way of making decisions. The syntax of the ternary operator is as follows:

[condition] ? [true expression] : [false expression]

The way this works is that [condition] is replaced with an expression that will return either true or false . If the result is true then the expression that replaces the [true expression] is evaluated. Conversely, if the result was false then the [false expression] is evaluated. Let's see this in action:

The above code example will evaluate whether x is greater than y. Clearly this will evaluate to false resulting in y being returned to the WriteLine method for display to the user.

Navigation menu

Personal tools.

  • View source
  • View history
  • iOS / iPhone / iPad
  • Objective-C
  • VMware Server
  • Xen Virtualization
  • Windows Server 2008
  • Red Hat Linux
  • Linux eBooks
  • Ubuntu Linux
  • Fedora Linux
  • Fedora Desktop
  • OpenSUSE Desktop
  • Visual Basic
  • Ad Blocking Survival
  • Web Development
  • Answertopia.com
  • Linuxtopia.org
  • Virtuatopia.com
  • eBook Store

c# boolean assignment operators

  • This page was last modified on 27 October 2016, at 20:03.
  • Copyright 2023 Payload Media, Inc. / Neil Smyth. All Rights Reserved.
  • Privacy policy
  • About Techotopia
  • Disclaimers
  • Mobile view

Powered by MediaWiki

C# Tutorial

C# examples, c# booleans.

Very often, in programming, you will need a data type that can only have one of two values, like:

  • TRUE / FALSE

For this, C# has a bool data type, which can take the values true or false .

Boolean Values

A boolean type is declared with the bool keyword and can only take the values true or false :

Try it Yourself »

However, it is more common to return boolean values from boolean expressions, for conditional testing (see below).

Boolean Expression

A Boolean expression returns a boolean value: True or False , by comparing values/variables.

This is useful to build logic, and find answers.

For example, you can use a comparison operator , such as the greater than ( > ) operator to find out if an expression (or a variable) is true:

Or even easier:

In the examples below, we use the equal to ( == ) operator to evaluate an expression:

Real Life Example

Let's think of a "real life example" where we need to find out if a person is old enough to vote.

In the example below, we use the >= comparison operator to find out if the age ( 25 ) is greater than OR equal to the voting age limit, which is set to 18 :

Cool, right? An even better approach (since we are on a roll now), would be to wrap the code above in an if...else statement, so we can perform different actions depending on the result:

Output "Old enough to vote!" if myAge is greater than or equal to 18 . Otherwise output "Not old enough to vote.":

The boolean value of an expression is the basis for all C# comparisons and conditions.

You will learn more about conditions ( if...else ) in the next chapter.

C# Exercises

Test yourself with exercises.

Fill in the missing parts to print the values True and False :

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]

Top Tutorials

Top references, top examples, get certified.

  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

Python Operators

Precedence and associativity of operators in python.

  • Python Arithmetic Operators
  • Difference between / vs. // operator in Python
  • Python - Star or Asterisk operator ( * )
  • What does the Double Star operator mean in Python?
  • Division Operators in Python
  • Modulo operator (%) in Python
  • Python Logical Operators
  • Python OR Operator
  • Difference between 'and' and '&' in Python
  • not Operator in Python | Boolean Logic

Ternary Operator in Python

  • Python Bitwise Operators

Python Assignment Operators

Assignment operators in python.

  • Walrus Operator in Python 3.8
  • Increment += and Decrement -= Assignment Operators in Python
  • Merging and Updating Dictionary Operators in Python 3.9
  • New '=' Operator in Python3.8 f-string

Python Relational Operators

  • Comparison Operators in Python
  • Python NOT EQUAL operator
  • Difference between == and is operator in Python
  • Chaining comparison operators in Python
  • Python Membership and Identity Operators
  • Difference between != and is not operator in Python

In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. 

  • OPERATORS: These are the special symbols. Eg- + , * , /, etc.
  • OPERAND: It is the value on which the operator is applied.

Types of Operators in Python

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Identity Operators and Membership Operators

Python Operators

Arithmetic Operators in Python

Python Arithmetic operators are used to perform basic mathematical operations like addition, subtraction, multiplication , and division .

In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.

Example of Arithmetic Operators in Python

Division operators.

In Python programming language Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. 

There are two types of division operators: 

Float division

  • Floor division

The quotient returned by this operator is always a float number, no matter if two numbers are integers. For example:

Example: The code performs division operations and prints the results. It demonstrates that both integer and floating-point divisions return accurate results. For example, ’10/2′ results in ‘5.0’ , and ‘-10/2’ results in ‘-5.0’ .

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is float, it returns output in float. It is also known as Floor division because, if any number is negative, then the output will be floored. For example:

Example: The code demonstrates integer (floor) division operations using the // in Python operators . It provides results as follows: ’10//3′ equals ‘3’ , ‘-5//2’ equals ‘-3’ , ‘ 5.0//2′ equals ‘2.0’ , and ‘-5.0//2’ equals ‘-3.0’ . Integer division returns the largest integer less than or equal to the division result.

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in Python is as follows:

  • P – Parentheses
  • E – Exponentiation
  • M – Multiplication (Multiplication and division have the same precedence)
  • D – Division
  • A – Addition (Addition and subtraction have the same precedence)
  • S – Subtraction

The modulus of Python operators helps us extract the last digit/s of a number. For example:

  • x % 10 -> yields the last digit
  • x % 100 -> yield last two digits

Arithmetic Operators With Addition, Subtraction, Multiplication, Modulo and Power

Here is an example showing how different Arithmetic Operators in Python work:

Example: The code performs basic arithmetic operations with the values of ‘a’ and ‘b’ . It adds (‘+’) , subtracts (‘-‘) , multiplies (‘*’) , computes the remainder (‘%’) , and raises a to the power of ‘b (**)’ . The results of these operations are printed.

Note: Refer to Differences between / and // for some interesting facts about these two Python operators.

Comparison of Python Operators

In Python Comparison of Relational operators compares the values. It either returns True or False according to the condition.

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In Python, the comparison operators have lower precedence than the arithmetic operators. All the operators within comparison operators have the same precedence order.

Example of Comparison Operators in Python

Let’s see an example of Comparison Operators in Python.

Example: The code compares the values of ‘a’ and ‘b’ using various comparison Python operators and prints the results. It checks if ‘a’ is greater than, less than, equal to, not equal to, greater than, or equal to, and less than or equal to ‘b’ .

Logical Operators in Python

Python Logical operators perform Logical AND , Logical OR , and Logical NOT operations. It is used to combine conditional statements.

Precedence of Logical Operators in Python

The precedence of Logical Operators in Python is as follows:

  • Logical not
  • logical and

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

Example: The code performs logical operations with Boolean values. It checks if both ‘a’ and ‘b’ are true ( ‘and’ ), if at least one of them is true ( ‘or’ ), and negates the value of ‘a’ using ‘not’ . The results are printed accordingly.

Bitwise Operators in Python

Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to operate on binary numbers.

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in Python is as follows:

  • Bitwise NOT
  • Bitwise Shift
  • Bitwise AND
  • Bitwise XOR

Here is an example showing how Bitwise Operators in Python work:

Example: The code demonstrates various bitwise operations with the values of ‘a’ and ‘b’ . It performs bitwise AND (&) , OR (|) , NOT (~) , XOR (^) , right shift (>>) , and left shift (<<) operations and prints the results. These operations manipulate the binary representations of the numbers.

Python Assignment operators are used to assign values to the variables.

Let’s see an example of Assignment Operators in Python.

Example: The code starts with ‘a’ and ‘b’ both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on ‘b’ . The results of each operation are printed, showing the impact of these operations on the value of ‘b’ .

Identity Operators in Python

In Python, is and is not are the identity operators both are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical. 

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

Example: The code uses identity operators to compare variables in Python. It checks if ‘a’ is not the same object as ‘b’ (which is true because they have different values) and if ‘a’ is the same object as ‘c’ (which is true because ‘c’ was assigned the value of ‘a’ ).

Membership Operators in Python

In Python, in and not in are the membership operators that are used to test whether a value or variable is in a sequence.

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

Example: The code checks for the presence of values ‘x’ and ‘y’ in the list. It prints whether or not each value is present in the list. ‘x’ is not in the list, and ‘y’ is present, as indicated by the printed messages. The code uses the ‘in’ and ‘not in’ Python operators to perform these checks.

in Python, Ternary operators also known as conditional expressions are operators that evaluate something based on a condition being true or false. It was added to Python in version 2.5. 

It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax :   [on_true] if [expression] else [on_false] 

Examples of Ternary Operator in Python

The code assigns values to variables ‘a’ and ‘b’ (10 and 20, respectively). It then uses a conditional assignment to determine the smaller of the two values and assigns it to the variable ‘min’ . Finally, it prints the value of ‘min’ , which is 10 in this case.

In Python, Operator precedence and associativity determine the priorities of the operator.

Operator Precedence in Python

This is used in an expression with more than one operator with different precedence to determine which operation to perform first.

Let’s see an example of how Operator Precedence in Python works:

Example: The code first calculates and prints the value of the expression 10 + 20 * 30 , which is 610. Then, it checks a condition based on the values of the ‘name’ and ‘age’ variables. Since the name is “ Alex” and the condition is satisfied using the or operator, it prints “Hello! Welcome.”

Operator Associativity in Python

If an expression contains two or more operators with the same precedence then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

The following code shows how Operator Associativity in Python works:

Example: The code showcases various mathematical operations. It calculates and prints the results of division and multiplication, addition and subtraction, subtraction within parentheses, and exponentiation. The code illustrates different mathematical calculations and their outcomes.

To try your knowledge of Python Operators, you can take out the quiz on Operators in Python . 

Python Operator Exercise Questions

Below are two Exercise Questions on Python Operators. We have covered arithmetic operators and comparison operators in these exercise questions. For more exercises on Python Operators visit the page mentioned below.

Q1. Code to implement basic arithmetic operations on integers

Q2. Code to implement Comparison operations on integers

Explore more Exercises: Practice Exercise on Operators in Python

Please Login to comment...

Similar reads.

  • python-basics
  • Python-Operators

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. C# Assignment Operator

    c# boolean assignment operators

  2. What are Boolean Operators? How To Teach Them + Examples

    c# boolean assignment operators

  3. 5 Boolean Operators You Need to Know

    c# boolean assignment operators

  4. Assignment Operators in C

    c# boolean assignment operators

  5. Operators in C# with Examples

    c# boolean assignment operators

  6. Beginner C#: Learn C#: Logic and Conditionals Cheatsheet

    c# boolean assignment operators

VIDEO

  1. Section 3 Operators Part 2 UNIT-4: INTRODUCTION TO DYNAMIC WEBSITES USING JAVASCRIPT 803

  2. C# 9 BOOLEAN 2

  3. Absolute Beginner C#

  4. C Programming

  5. C#

  6. 13-Assignment Operator in C#

COMMENTS

  1. Boolean logical operators

    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.

  2. Why are there no ||= or &&= operators in C#?

    We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators. ... Using &= on boolean values in C#. 2. Why is ~= the only non-logical assignment operator missing in C++? 0. The &= Operator Equivalent. Related. 3.

  3. boolean-logical-operators.md

    The logical Boolean operators perform logical operations with bool operands. The operators include the unary logical negation (!), ... For the complete list of C# operators ordered by precedence level, ... When a binary operator is overloaded, the corresponding compound assignment operator is also implicitly overloaded. A user-defined type can ...

  4. 5.2. Logical Operators

    5.2.1.1. Logical AND¶. A compound boolean expression is a boolean expression built out of smaller boolean expressions. 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.

  5. Essential C#: Boolean Expressions

    Although at first glance this code appears to check whether input equals 9, Chapter 1 showed that = represents the assignment operator, not a check for equality. The return from the assignment operator is the value assigned to the variable—in this case, 9.However, 9 is an int, so it does not qualify as a Boolean expression and is not allowed by the C# compiler.

  6. C# Logical Operators

    As with comparison operators, you can also test for True or False values with logical operators. Logical operators are used to determine the logic between variables or values: Operator. Name. Description. Example. Try it. &&. Logical and.

  7. C# operator

    C# compound assignment operators. The compound assignment operators consist of two operators. They are shorthand operators. a = a + 3; a += 3; The += compound operator is one of these shorthand operators. The above two expressions are equal. Value 3 is added to the a variable. Other compound operators are:

  8. C# Operators

    Operators in C# are some special symbols that perform some action on operands. In mathematics, the plus symbol (+) do the sum of the left and right numbers. In the same way, C# includes various operators for different types of operations. The following example demonstrates the + operator in C#. Example: + Operator. int x = 5 + 5; int y = 10 + x;

  9. Bitwise assignment operators in C#

    But on a bool, it's a logical operation: bool a = true; bool b = false; a |= b; Console.WriteLine(a); // outputs true How do the ^= , &= and |= operators decide which manipulation to use when being applied to different data types?

  10. C#

    Assignment operators for assigning values to variables. Comparison operators for comparing two values. Logical operators for combining Boolean values. Bitwise operators for manipulating the bits of a number. Arithmetic Operators. C# has the following arithmetic operators: Addition, +, returns the sum of two numbers.

  11. Chapter 3 C# Operators

    Assignment =, Addition assignment +=, Subtraction assignment -=, multiplication assignment *=, division assignment /= Logical Operators: These are used in boolean operators, in condition statements. And &&, Or ||, Not ! Logical AND: Let's assume we have two variables: x and y. In C#, the logical AND operator is indicated by &&. Boolean ...

  12. Short circuit on |= and &= assignment operators in C#

    The C# specification for compound operators says: 7.17.2 Compound assignment An operation of the form x op= y is processed by applying binary operator overload resolution (§7.3.4) as if the operation was written x op y .

  13. C Sharp Operators and Expressions

    As with the compound assignment operators described in the previous section, consider the following C# code fragment: x = x + 1; // Increase value of variable x by 1. x = x - 1; // Decrease value of variable y by 1. These expressions increment and decrement the value of x by 1. Instead of using this approach it is quicker to use the ++ and ...

  14. C# Booleans

    A Boolean expression returns a boolean value: True or False, by comparing values/variables. This is useful to build logic, and find answers. For example, you can use a comparison operator, such as the greater than ( >) operator to find out if an expression (or a variable) is true:

  15. Using &= on boolean values in C#

    As you can read here, both & and && are defined for bools as "logical and", but && will short-circuit: in case the first operand is false the expression on the right will not be evaluated. Regardless what the outcome of the expression on the right is, the result of the && expression will remain false.This is usually a "performance hack" in the first place, but if the right expression has side ...

  16. Python Operators

    Assignment Operators in Python. Let's see an example of Assignment Operators in Python. Example: The code starts with 'a' and 'b' both having the value 10. It then performs a series of operations: addition, subtraction, multiplication, and a left shift operation on 'b'.

  17. Does the assignment operator in c# take any other value other than bool

    The lifted operator considers two null values equal, and a null value unequal to any non-null value. If both operand are non-null, the lifted operator unwraps the operands and applies the underlying operator to produce the bool result. For the relational operators < > <= >=