clear:
int num1 = 5;
int num2 = 5;
int result;
result = num1++;
Console.WriteLine(num1); //---6---
Console.WriteLine(result); //---5---
result = ++num2;
Console.WriteLine(num2); //---6---
Console.WriteLine(result); //---6---
As you can see, if you use the postfix operator (num1++
), the value of num1
is assigned to result before the value of num1
is incremented by 1. In contrast, the prefix operator (++num2
) first increments the value of num2
by 1 and then assigns the new value of num2
(which is now 6) to result
.
Here's another example:
int num1 = 5;
int num2 = 5;
int result;
result = num1++ + ++num2;
Console.WriteLine(num1); //---6---
Console.WriteLine(num2); //---6---
Console.WriteLine(result); //---11---
In this case, both num1
and num2
are initially 5. Because a postfix operator is used on num1
, its initial value of 5 is used for adding. And because num2
uses the prefix operator, its value is incremented before adding, hence the value 6 is used for adding. This adds up to 11 (5 + 6). After the first statement, both num1
and num2
would have a value of 6.
Relational Operators
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:
{
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.
Logical Operators
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 |
---|---|
&& |