Chapter 5 Operators

What’s in This Chapter

  • Arithmetic, concatenation, comparison, logical, and bitwise operators
  • Operator precedence
  • DateTime and TimeSpan 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.

OperatorPurposeExampleResult
++Incrementx++ or ++xSets x = x + 1
--Decrementx-- or --xSets x = x - 1
Negation-xSets x = -x
+Unary plus+xSets x = +x (leaves x unchanged)
*Multiplication2 * 36
/Division3.0 / 21.5
%Modulus17 mod 52
+Addition2 + 35
-Subtraction3 - 21
<<Bit left shift10110111 << 101101110
>>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.