Chapter 5 Operators
What’s in This Chapter
- Arithmetic, concatenation, comparison, logical, and bitwise operators
- Operator precedence
DateTime
andTimeSpan
operators- Operator overloading
- Type conversion operators
Wrox.com Downloads for This Chapter
Please note that all the code examples for this chapter are available as a part of this chapter’s code download on the book’s website at www.wrox.com/go/csharp5programmersref on the Download Code tab.
An operator is a basic code element that performs some operation on one or more values to create a result. The values the operator acts upon are operands. For example, in the following statement, the operator is + (addition), the operands are B
and C
, and the result is assigned to the variable A
.
A = B + C
C# operators fall into five categories: arithmetic, concatenation, comparison, logical, and bitwise. This chapter first explains these categories and the operators they contain; it then discusses other operator issues such as precedence, assignment operators, and operator overloading.
Arithmetic Operators
The following table lists the arithmetic operators provided by C#. Most of these should be familiar to you.
Operator | Purpose | Example | Result |
++ | Increment | x++ or ++x | Sets x = x + 1 |
-- | Decrement | x-- or --x | Sets x = x - 1 |
– | Negation | -x | Sets x = -x |
+ | Unary plus | +x | Sets x = +x (leaves x unchanged) |
* | Multiplication | 2 * 3 | 6 |
/ | Division | 3.0 / 2 | 1.5 |
% | Modulus | 17 mod 5 | 2 |
+ | Addition | 2 + 3 | 5 |
- | Subtraction | 3 - 2 | 1 |
<< | Bit left shift | 10110111 << 1 | 01101110 |
>> | Bit right ... |
Get C# 5.0 Programmer's Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.