In C#, operators are special symbols or keywords that are used to perform operations on variables and values. Operators are an essential part of C# programming, enabling developers to manipulate data and variables efficiently.
An operator in C# performs specific mathematical, logical, or bitwise operations, such as addition, subtraction, comparison, and more. They work with operands (variables, values, or expressions) to produce a result.
Every programming language uses operators, through which we can perform different actions on the data.
Operators allow the processing of primitive data types and objects. They take as input one or more operands and return some value as a result.
1. Arithmetic Operators
These operators are used for performing basic mathematical operations.
Example:
int a = 20;
int b = 5;
Console.WriteLine(a + b); // Output: 25 (Addition)
Console.WriteLine(a - b); // Output: 15 (Subtraction)
Console.WriteLine(a * b); // Output: 100 (Multiplication)
Console.WriteLine(a / b); // Output: 4 (Division)
Console.WriteLine(a % b); // Output: 0 (Remainder)
Note:
- When dividing two integers (int type), C# performs integer division and discards any fractional part.
- To get a floating-point result, one of the operands must be a floating-point type (e.g., double or float).
2. Relational (Comparison) Operators
These operators are used to compare two values. They return a boolean value (true or false).
Example:
int a = 20;
int b = 5;
Console.WriteLine(a == b); // Output: false
Console.WriteLine(a != b); // Output: true
Console.WriteLine(a > b); // Output: true
Console.WriteLine(a < b); // Output: false
Console.WriteLine(a >= b); // Output: true
Console.WriteLine(a <= b); // Output: false
3. Logical Operators
Logical operators are used to combine conditional statements.
Example:
bool a = true;
bool b = false;
Console.WriteLine(a && b); // Output: False (Both must be true)
Console.WriteLine(a || b); // Output: True (At least one is true)
Console.WriteLine(!a); // Output: False (Reverses the value)
4. Assignment Operators
These are used to assign values to variables. Some assignment operators combine arithmetic operations with assignment.
Example:
int a = 20;
a += 10; // a = a + 10 => num = 30
a -= 5; // a = a - 5 => a = 25
a *= 2; // a = a * 2 => a = 50
a /= 5; // a = a / 5 => a = 10
Console.WriteLine(a); // Output: 10
5. Ternary Operator
This is a shorthand for an if-else statement.
Syntax:
condition ? expression_if_true : expression_if_false
Example:
int age = 19;
string result = (age >= 18) ? 'Adult': 'Not Adult';
Console.WriteLine(result); // Output: Adult
6. Unary Operators
These operators operate on a single operand.
Example:
int x = 20;
Console.WriteLine(++x); // Output: 21 (Pre-increment)
Console.WriteLine(x++); // Output: 21 (Post-increment)
Console.WriteLine(x); // Output: 22 (x is now 22)