The arithmetic operators (+, -, *, /, %) are defined for all numeric types.
Operator | Meaning |
---|---|
+ | Addition |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Remainder after division |
The increment and decrement operators (++, --) increment and decrement numeric types by 1.
The operator can either follow or precede the variable, depending on whether we want its value before or after the increment/decrement.
For example:
int x = 0, y = 0;
Console.WriteLine (x++); // Outputs 0; x is now 1
Console.WriteLine (++y); // Outputs 1; y is now 1
Division operations on integral types always truncate remainders.
Dividing by a variable whose value is zero generates a runtime error.
Dividing by the literal or constant 0 generates a compile-time error.
At runtime, arithmetic operations on integral types can overflow.
For example, decrementing the minimum possible int
value results in the maximum possible int
value:
int a = int.MinValue;
a--;
Console.WriteLine (a == int.MaxValue); // True
The checked
operator tells the runtime to
generate an OverflowException
rather than
overflowing silently in case of overflow.
The checked
operator affects expressions with the ++, --, +, -, *, /,
and explicit conversion operators between integral types.
The checked
operator has no effect on the double and float types.
The checked
operator has no effect on the decimal type which is always checked.
checked
can be used around either an expression or a statement block.
For example:
int a = 1000000;
int b = 1000000;
//from w w w . j a v a 2s. c o m
int c = checked (a * b); // Checks just the expression.
// Checks all expressions in statement block.
checked{
...
c = a * b;
...
}
We can check all arithmetic overflow for a
program by compiling with the /checked+
command-line switch.
To disable overflow checking
for specific expressions or statements, use the unchecked
operator.
For example, the following code will not throw exceptions-even if compiled
with /checked+
:
int x = int.MaxValue;
int y = unchecked (x + 1);
unchecked { int z = x + 1; }
Regardless of the /checked
compiler switch, expressions evaluated at compile time
are always overflow-checked-unless we apply the unchecked
operator:
int x = int.MaxValue + 1; // Compile-time error
int y = unchecked (int.MaxValue + 1); // No errors
C# supports the following bitwise operators:
Operator | Meaning | Sample expression | Result |
---|---|---|---|
~ | Complement | ~0xfU | 0xfffffff0U |
& | And | 0xf0 & 0x33 | 0x30 |
| | Or | 0xf0 | 0x33 | 0xf3 |
^ | Exclusive Or | 0xff00 ^ 0x0ff0 | 0xf0f0 |
<< | Shift left | 0x20 << 2 | 0x80 |
>> | Shift right | 0x20 >> 1 | 0x10 |