Operators

C# Operators

Operators in C# are symbols used to perform operations on variables and values. These include mathematical, logical, comparison, and assignment operators, among others.


Types of Operators

1. Arithmetic Operators

Perform basic mathematical operations.

Operator
Description
Example
Result

+

Addition

10 + 3

13

-

Subtraction

10 - 3

7

*

Multiplication

10 * 3

30

/

Division

10 / 3

3

%

Modulus (remainder)

10 % 3

1

Example

int a = 10, b = 3;
Console.WriteLine(a + b); // Output: 13
Console.WriteLine(a % b); // Output: 1

2. Relational (Comparison) Operators

Compare two values.

Operator
Description
Example
Result

>

Greater than

7 > 10

False

<

Less than

7 < 10

True

>=

Greater than or equal

10 >= 7

True

<=

Less than or equal

10 <= 7

False

==

Equal to

7 == 7

True

!=

Not equal to

7 != 10

True

Example


3. Logical Operators

Combine multiple conditions.

Operator
Description
Example
Result

&&

Logical AND

true && false

False

||

Logical OR

true || false

True

!

Logical NOT

!true

False

Example


4. Assignment Operators

Assign values to variables.

Operator
Description
Example
Result

=

Assign

x = 10

10

+=

Add and assign

x += 5

15

-=

Subtract and assign

x -= 3

12

*=

Multiply and assign

x *= 2

24

/=

Divide and assign

x /= 2

12

%=

Modulus and assign

x %= 5

2

Example


5. Unary Operators

Operate on a single operand.

Operator
Description
Example
Result

++

Increment

++y

6

--

Decrement

--y

4

!

Logical NOT

!true

False

Example


6. Bitwise Operators

Perform operations on binary representations.

Operator
Description
Example
Result

&

Bitwise AND

5 & 3 (0101 & 0011)

1

|

Bitwise OR

5 | 3 (0101 | 0011)

7

^

Bitwise XOR

5 ^ 3 (0101 ^ 0011)

6

~

Bitwise Complement

~5 (inverts 0101)

-6

<<

Left Shift

5 << 1 (0101 → 1010)

10

>>

Right Shift

5 >> 1 (0101 → 0010)

2

Example


Summary

  • Arithmetic: Perform math operations (+, -, *, /, %).

  • Relational: Compare values (>, <, ==, !=).

  • Logical: Combine conditions (&&, ||, !).

  • Assignment: Assign values (=, +=, *=, etc.).

  • Unary: Operate on single operands (++, --, !).

  • Bitwise: Work with binary values (&, |, ^, ~, <<, >>).

C# operators enable efficient computation, condition checks, and value manipulation across a variety of programming tasks.

Last updated