C# Basics

Understanding Operators

Operators in C#

Operators are special symbols that perform operations on one or more operands. C# supports a rich set of operators to manipulate data and control program flow.

Arithmetic Operators

These operators are used for mathematical calculations.

Operator Description Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulo (Remainder) a % b

Assignment Operators

These operators are used to assign values to variables.

Operator Description Example
= Simple assignment x = 10;
+= Add and assign x += 5; (same as x = x + 5;)
-= Subtract and assign x -= 3; (same as x = x - 3;)
*= Multiply and assign x *= 2; (same as x = x * 2;)
/= Divide and assign x /= 4; (same as x = x / 4;)
%= Modulo and assign x %= 3; (same as x = x % 3;)

Comparison (Relational) Operators

These operators are used to compare two values and return a boolean result (true or false).

Operator Description Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater than or equal to a >= b
<= Less than or equal to a <= b

Logical Operators

These operators are used to combine or modify boolean expressions.

Operator Description Example
&& Logical AND condition1 && condition2
|| Logical OR condition1 || condition2
! Logical NOT !condition

Increment and Decrement Operators

These operators increase or decrease the value of a variable by 1.

Operator Description Example
++ Increment i++; or ++i;
-- Decrement i--; or --i;

Note: The position of the operator (prefix ++i vs. postfix i++) affects when the value is incremented relative to the expression's evaluation.

Other Operators

C# also includes several other useful operators, such as:

Example Usage

Let's see how some operators work together.


int a = 10;
int b = 5;
int sum = a + b; // sum is 15
bool isEqual = (a == b); // isEqual is false
bool isGreater = (a > b); // isGreater is true

Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Are they equal? {isEqual}");
Console.WriteLine($"Is a greater than b? {isGreater}");

int x = 20;
x += 5; // x is now 25
Console.WriteLine($"New value of x: {x}");

bool condition1 = true;
bool condition2 = false;
bool result = condition1 && condition2; // result is false
Console.WriteLine($"Logical AND result: {result}");
            

Understanding and using operators effectively is fundamental to writing C# code. They form the building blocks for calculations, comparisons, and logical decision-making within your programs.

Continue to the next topic: Control Flow.