You use relational operators to compare two values and the result of the comparison is a Boolean value — true or false. The following table lists all of the relational operators available in C#.
Operator |
Description |
== |
Equal |
!= |
Not equal |
> |
Greater than |
>= |
Greater than or equal to |
< |
Lesser than |
<= |
Lesser than or equal to |
The following statements compare the value of num with the numeric 5 using the various relational operators:
int num = 5;
Console.WriteLine(num == 5); //---True---
Console.WriteLine(num != 5); //---False---
Console.WriteLine(num > 5); //---False---
Console.WriteLine(num >= 5); //---True---
Console.WriteLine(num < 5); //---False---
Console.WriteLine(num <= 5); //---True---
A common mistake with the equal relational operator is omitting the second = sign. For example, the following statement prints out the numeric 5 instead of True:
Console.WriteLine(num = 5);
A single = is the assignment operator.
C programmers often make the following mistake of using a single = for testing equality of two numbers:
if (num = 5) //---use == for testing equality---
{
Console.WriteLine("num is 5");
}
Fortunately, the C# compiler will check for this mistake and issue a "Cannot implicitly convert type 'int' to 'bool'" error.
C# supports the use of logical operators so that you can evaluate multiple expressions. The following table lists the logical operators supported in C#.
Operator |
Description |
&& |
And |
|| |
Or |
! |
Not |
For example, consider the following code example:
if (age < 12 || height > 120) {
Console.WriteLine("Student price applies");
}
In this case, student price applies if either the age is less than 12, or the height is less than 120cm. As long as at least one of the conditions evaluates to true, the statement is true. Following is the truth table for the Or ( ||
) operator.
Operand A |
Operand B |
Result |
false |
false |
false |
false |
true |
true |
true |
false |
true |
true |
true |
true |
However, if the condition is changed such that student price applies only if a person is less than 12 years old and with height less than 120cm, the statement would be rewritten as:
if (age < 12 && height > 120) {
Console.WriteLine("Student price applies");
}
The truth table for the And ( &&
) operator follows.
Operand A |
Operand B |
Result |
false |
false |
false |
false |
true |
false |
true |
false |
false |
true |
true |
true |
The Not operator ( !
) negates the result of an expression. For example, if student price does not apply to those more than 12 years old, you could write the expression like this:
if (!(age >= 12))
Console.WriteLine("Student price does not apply");
Following is the truth table for the Not operator.
Operand A |
Result |
false |
true |
true |
false |
Short-Circuit Evaluation
C# uses short-circuiting when evaluating logical operators. In short-circuiting, the second argument in a condition is evaluated only when the first argument is not sufficient to determine the value of the entire condition. Consider the following example:
int div = 0; int num = 5;
if ((div == 0) || (num / div == 1)) {
Console.WriteLine(num); //---5---
}
Here the first expression evaluates to true, so there is no need to evaluate the second expression (because an Or expression evaluates to true as long as at least one expression evaluates to true). The second expression, if evaluated, will result in a division-by-zero error. In this case, it won't, and the number 5 is printed.
If you reverse the placement of the expressions, as in the following example, a division-by-zero error occurs:
if ((num / div == 1) || (div == 0)) {
Console.WriteLine(num);
}
Short-circuiting also applies to the &&
operator — if the first expression evaluates to false, the second expression will not be evaluated because the final evaluation is already known.
C# supports five mathematical operators, shown in the following table.
Operator |
Description |
+ |
Addition |
- |
Subtraction |
/ |
Division |
* |
Multiplication |
% |
Modulus |
One interesting thing about the division operator ( /
) is that when you divide two integers, the fractional part is discarded:
int num1 = 6;
int num2 = 4;
double result = num1 / num2;
Console.WriteLine(result); //---1---
Here both num1
and num2
are integers and hence after the division result only contains the integer portion of the division. To divide correctly, one of the operands must be a noninteger, as the following shows:
int num1 = 6;
double num2 = 4;
double result = num1 / num2;
Console.WriteLine(result); //---1.5---
Alternatively, you can use type casting to force one of the operands to be of type double so that you can divide correctly:
int num1 = 6;
int num2 = 4;
double result = (double)num1 / num2;
Console.WriteLine(result); //---1.5---
The modulus operator ( %
) returns the reminder of a division:
int num1 = 6;
int num2 = 4;
int remainder = num1 % num2;
Console.WriteLine(remainder); //---2---
The %
operator is commonly used for testing whether a number is odd or even, like this:
if (num1 % 2 == 0) Console.WriteLine("Even");
else Console.WriteLine("Odd");
When you use multiple operators in the same statement, you need be aware of the precedence of each operator (that is, which operator will evaluate first). The following table shows the various C# operators grouped in the order of precedence. Operators within the same group have equal precedence (operators include some keywords).
Category |
Operators |
Primary |
x.y f(x) a[x] x++ x-- new typeof checked unchecked |
Unary |
+ - ! ~ ++x --x (T)x |
Multiplicative |
* / % |
Additive |
+ - |
Shift |
<< >> |
Relational and type testing |
< > <= >> is as |
Equality |
== != |
Logical AND |
& |
Logical XOR |
^ |
Logical OR |
| |
Conditional AND |
&& |
Conditional OR |
|| |
Conditional |
?: |
Assignment |
= *= /= %= += -= <<= >>= &= ^= | = |
When you are in doubt of the precedence of two operators, always use parentheses to force the compiler to evaluate the expression first. For example, the formula to convert a temperature from Fahrenheit to Celsius is:
Читать дальше