Operators in C# are symbols that perform specific operations on one or more operands. They are essential for manipulating data and controlling program flow. This guide will introduce you to the various types of operators in C# and their usage.
C# provides several categories of operators:
Arithmetic operators perform mathematical calculations on numeric operands.
Operator | Description | Example |
---|---|---|
+ | Addition | int sum = 5 + 3; // 8 |
- | Subtraction | int difference = 10 - 4; // 6 |
* | Multiplication | int product = 3 * 4; // 12 |
/ | Division | int quotient = 15 / 3; // 5 |
% | Modulus (remainder) | int remainder = 17 % 5; // 2 |
Comparison operators compare two values and return a boolean result.
Operator | Description | Example |
---|---|---|
== | Equal to | bool isEqual = (5 == 5); // true |
!= | Not equal to | bool isNotEqual = (5 != 3); // true |
> | Greater than | bool isGreater = (7 > 3); // true |
< | Less than | bool isLess = (2 < 5); // true |
>= | Greater than or equal to | bool isGreaterOrEqual = (5 >= 5); // true |
<= | Less than or equal to | bool isLessOrEqual = (3 <= 4); // true |
Logical operators perform boolean operations on operands.
Operator | Description | Example |
---|---|---|
&& | Logical AND | bool result = (true && false); // false |
|| | Logical OR | bool result = (true || false); // true |
! | Logical NOT | bool result = !true; // false |
Assignment operators assign values to variables.
Operator | Description | Example |
---|---|---|
= | Simple assignment | int x = 5; |
+= | Add and assign | x += 3; // Equivalent to x = x + 3; |
-= | Subtract and assign | x -= 2; // Equivalent to x = x - 2; |
*= | Multiply and assign | x *= 4; // Equivalent to x = x * 4; |
/= | Divide and assign | x /= 2; // Equivalent to x = x / 2; |
The conditional operator (?:) is a ternary operator that evaluates a boolean expression and returns one of two values based on the result.
int age = 20;
string status = (age >= 18) ? "Adult" : "Minor";
// status will be "Adult"
Operators in C# follow a specific order of precedence. When multiple operators appear in an expression, the operators with higher precedence are evaluated first.
It's important to use parentheses to explicitly define the order of operations in complex expressions, improving code readability and avoiding potential errors.
To deepen your understanding of C# operators and their usage, explore these related topics:
By mastering C# operators, you'll be able to write more efficient and expressive code, manipulate data effectively, and control program flow with precision.