Understanding Operators
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.
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 |
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; ) |
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 |
These operators are used to combine or modify boolean expressions.
Operator | Description | Example |
---|---|---|
&& |
Logical AND | condition1 && condition2 |
|| |
Logical OR | condition1 || condition2 |
! |
Logical NOT | !condition |
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.
C# also includes several other useful operators, such as:
condition ? value_if_true : value_if_false
.
(e.g., Console.WriteLine
)is
and as
??
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.