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

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 .

BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy . This message is for compliance with the UK ICO law .

C# Programming

C# Boolean Operators

The eighth part of the C# Fundamentals tutorial moves away from arithmetic and takes a first look at the Boolean data type and its available operators. Boolean data is used extensively in programming and an understanding of its features is essential.

A Review of the Boolean Data Type

In the third part of the C# Fundamentals tutorial I introduced the Boolean data type. A Boolean variable is capable of storing just two values, true or false , also known as truth values . The following examples show the simple assignment of Boolean variables, which are declared using the bool keyword.

Boolean Logic Operators

The Boolean data type has its own set of logical operators . These allow you to test or adjust the value of a Boolean variable. The resultant values may be used in conditional statements to determine the flow through the code. Conditional programming will be examined later in the tutorial. For this article, the next sections describe the various available operators.

Equivalence Operator

The equivalence , or equality , operator is a binary operator , in that it operates on two values or operands . The equivalence operator compares the two operands and returns a Boolean value indicating if they match exactly. The operator symbol for equivalence is a double-equals signs (==).

Inequality Operator

The inequality operator compares two operands and returns true if the two values are different. The operator provides the opposite functionality to the equivalence operator. The operator's symbol is an exclamation mark and an equals signs (!=). It is read as " not equal to ".

NOT Operator

The NOT operator is a unary operator , as it operates on a single operand. The NOT operator inverts the value of a Boolean value. If the original value is true then the returned value is false; if the original value is false, the return value is true. The NOT operation is often known as the binary complement .

AND Operator

The AND operator is used to compare two Boolean values. It returns true if both of the operands are true. This can be represented by the following truth table, which shows the two operands and the result of every possible AND operation.

The AND operator is represented by the ampersand character (&):

OR Operator

The OR operator is similar to AND, as it is used to compare two Boolean values. The OR operator returns true if either of the operands are true. This can be represented by the following truth table.

The OR operator is represented by the bar character (|):

RSS Feed

c# boolean assignment operators

Conditional operator(?:) in C#

Conditional operator (?:) in C# is used as a single line if-else assignment statement, it is also known as Ternary Operator in C#. It evaluates a Boolean expression and on the basis of the evaluated True and False value, it executes corresponding statement.

Precisely, conditional operator (?:) can be explained as follows.

It has three operands: condition , consequence and alternative . The conditional expression returns a Boolean value as true or false . If the value is true , then it evaluates the consequence expression. If false , then it evaluates the alternative expression.

Syntax of c onditional operator (?:) in C#

It uses a question mark ( ? ) operator and a colon ( : )  operator , the general format is as follows.

Condition ( Boolean expression ) ? consequence ( if true ) : alternative ( if false )

Lets look at below example, here we are doing a conditional check and based on the true/false, assigning the variable value to taxPercentage  .

In above case, If isSiniorCitizen == true then taxPercentage  will be 20 else it will be 30 , in the above case it sets to 20 since we have already set the boolean value isSiniorCitizen = true  .

Example of (?:) operator in C#

Lets look at an example.

In above example code snippet, the boolean expression String . IsNullOrEmpty ( LastName ) returns True value, so the consequence statement executes, which gives output as “Ramesh” . 

Conditional operator figure 1.0

Lets take another example, where conditional expression returns False value.

In above example, the boolean expression String . IsNullOrEmpty ( LastName  returns False value, so the alternative statement ( FirstName + " " + LastName ) executes, which gives output as “Ramesh Kumar” . 

Conditional operator figure 1.1

Conditional operator(?:) vs Null Coalescing (??) Operator ?

In the case of Null coalescing operator (??) , It checks for the null-ability of first operand and based on that assigns the value. If the first operand value is null then assigns second operand else assigns the first.

Lets have a look at below expression.

In the above example, If y is null then z is assigned to x else y . For more details on Null coalescing operator (??) , please check here . 

We can rewrite above expression using conditional operator (?:) as follows.

Here, if y is null (that means if the expression ( Y == null )  return true) then assign z else assign y to x .

In single line if else statement:

Lets take below if-else statement.

In above if-else statement, boolean expression determines variable assignment. This is the right scenario where we can use Conditional operator (?:) as a replacement of if-else statement.

In above example, here in this case i >= 5   is a True condition, hence this statement  10 * 5 executes and 50 is assigned to x . Lets take below example.

In above example, here condition i >= 5 is  False , hence 10 * 4   executes and 40 is assigned to x .

Nested conditional operator (?:) in C#

In some scenarios, where there are cascading if-else conditions of variable assignment. We can use chaining conditional operators to replace cascading if-else conditions to a single line, by including a conditional expression as a second statement.

Let’s take below example of cascading/nested if-else statement.

Above cascading if-else condition can be re-written as follows.

Share this:

One thought on “ conditional operator(:) in c# ”.

Add Comment

VB will use If(Condition, TruePart, FalsePart) if not same types then IIf can be used.

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed .

Discover more from

Subscribe now to keep reading and get access to the full archive.

Type your email…

Continue reading

IMAGES

  1. Boolean Operators in C++

    c# boolean assignment operators

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

    c# boolean assignment operators

  3. Operators in C# with Examples

    c# boolean assignment operators

  4. Operators In C Logicmojo

    c# boolean assignment operators

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

    c# boolean assignment operators

  6. C programming +=

    c# boolean assignment operators

VIDEO

  1. #20 Assignment Operators in C#

  2. C Programming

  3. C#

  4. gcc options

  5. CSE-160-D01 2024SP 02/28/2024

  6. C++ Assignment Operators Practice coding

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

  3. 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.

  4. 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.

  5. 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:

  6. C# Boolean Operators

    A Review of the Boolean Data Type. In the third part of the C# Fundamentals tutorial I introduced the Boolean data type. A Boolean variable is capable of storing just two values, true or false, also known as truth values.The following examples show the simple assignment of Boolean variables, which are declared using the bool keyword.

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

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

  9. Learn about C# Operators and Their Uses

    C# Operators. In C#, an operator is a program element that is applied to one or more operands in an expression or statement. Operators that take one operand, such as the increment operator (++) or new, are referred to as unary operators. Operators that take two operands, such as arithmetic operators (+,-,*,/), are referred to as binary operators.

  10. Mastering C# Operators: Your Guide to Efficient Code Manipulation

    Here are the primary arithmetic operators in C#: 1. Addition ' + '. The addition operator is used to add two values together: int sum = 5 + 3; // sum will be 8. 2. Subtraction ' - '. The ...

  11. Conditional operator(?:) in C#

    Conditional operator (?:) in C# is used as a single line if-else assignment statement, it is also known as Ternary Operator in C#. It evaluates a Boolean expression and on the basis of the evaluated True and False value, it executes corresponding statement. Precisely, conditional operator (?:) can be explained as follows.

  12. Boolean Assignment Operators in C#

    9. Docs: Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true. In math, this is called mutually exclusive.

  13. 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 ...

  14. Shorthand Operators in C#: Streamlining Your Code

    As a C# developer, you've undoubtedly encountered the need for concise and efficient code. Shorthand operators come to the rescue, offering a more streamlined approach to writing common expressions.

  15. Overloading assignment operator in C#

    There is already a special instance of overloading = in place that the designers deemed ok: property setters. Let X be a property of foo. In foo.X = 3, the = symbol is replaced by the compiler by a call to foo.set_X(3). You can already define a public static T op_Assign(ref T assigned, T assignee) method. All that is left is for the compiler to ...