C sharp - Relational and Assignment Operators
1. Relational Operators
Definition:
Relational operators are used to compare two values. They return a boolean result (true
or false
).
List of Relational Operators in C#:
Operator | Description | Example | Result |
---|---|---|---|
== |
Equal to | 5 == 5 |
true |
!= |
Not equal to | 5 != 3 |
true |
> |
Greater than | 10 > 8 |
true |
< |
Less than | 4 < 7 |
true |
>= |
Greater than or equal to | 6 >= 6 |
true |
<= |
Less than or equal to | 2 <= 3 |
true |
Example:
int a = 10;
int b = 20;
Console.WriteLine(a == b); // false
Console.WriteLine(a != b); // true
Console.WriteLine(a < b); // true
2. Assignment Operators
Definition:
Assignment operators are used to assign values to variables.
List of Assignment Operators in C#:
Operator | Description | Example | Equivalent To |
---|---|---|---|
= |
Assign | a = 5 |
|
+= |
Add and assign | a += 3 |
a = a + 3 |
-= |
Subtract and assign | a -= 2 |
a = a - 2 |
*= |
Multiply and assign | a *= 4 |
a = a * 4 |
/= |
Divide and assign | a /= 2 |
a = a / 2 |
%= |
Modulus and assign | a %= 3 |
a = a % 3 |
Example:
int x = 10;
x += 5; // x = x + 5 => 15
x *= 2; // x = x * 2 => 30
Console.WriteLine(x); // Output: 30