Operators: Arithmetic, Logical, and Conditional in C#

The C# operators used for arithmetic operations, bit manipulation, and conditional program flow should be familiar to all programmers. This section presents an overview of these operators that is meant to serve as a syntactical reference.

Arithmetic Operators

Table 2-4 summarizes the basic numerical operators. The precedence in which these operators are applied during the evaluation of an expression is shown in parentheses, with 1 being the highest precedence.

Table 2-4. Numerical Operators

Operator

Description

Example

+

-

(3)

Addition

Subtraction

int x = y + 10;

*

/

%

(2)

Multiplication

Division,

Modulo

int x = 60;

int y = 15;

int z = x * y / 2;  // 450

y = x % 29 ;  // remainder is 2

++

--

(1)

Prefix/postfix

Increment/decrement

x = 5;

Console.WriteLine(x++) // x = 5 

Console.WriteLine(++x) // x = 6

~

(1)

Bitwise complement

int x = ~127; // returns -128

>>

<<

(4)

Shift right

Shift left

byte x = 10; // binary 10 is 01010

int result = x << 1; // 20 = 10100

result = x >> 2;     //  5 = 00101

Works with byte, char, short, int, and long

&

|

^

(5-6-7)

Bitwise AND

Bitwise OR

Bitwise XOR

byte x = 12;        //    001100

byte y = 11;        //    001011

int result = x & y; //8 = 001000

result = x ^ y;     //7 = 000111

Leave a Reply

Your email address will not be published. Required fields are marked *