Operators
An operator in C# is a symbol that tells the compiler to perform specific mathematical, logical, or data manipulations on operands (variables or values).
C# provides a rich set of built-in operators. Below are the primary categories of C# Operators.
Operator Categories in C#
| Operator Category | Purpose | Examples |
|---|---|---|
| Arithmetic | Perform mathematical calculations | +, -, *, /, % |
| Relational / Comparison | Compare two values | ==, !=, >, <, >=, <= |
| Logical | Combine boolean conditions | &&, ||, ! |
| Assignment | Assign or update values | =, +=, -=, *=, /= |
| Increment / Decrement | Increase or decrease a value | ++, -- |
| Ternary | Short form of if-else | ?: |
| Null-Coalescing | Handle null values | ??, ??= |
-
Arithmetic Operators
Used to perform common mathematical computations on numeric types.
- + (Addition): Adds two values.
- - (Subtraction): Subtracts one value from another.
- * (Multiplication): Multiplies two values.
- / (Division): Divides one value by another.
- % (Modulus): Returns the division remainder.
Example
C#using System; int a = 10; int b = 3; Console.WriteLine(a + b); // Output: 13 Console.WriteLine(a - b); // Output: 7 Console.WriteLine(a * b); // Output: 30 Console.WriteLine(a / b); // Output: 3 (Integer division drops decimal part) Console.WriteLine(a % b); // Output: 1 (Remainder of 10 / 3)Important: When two integer values are divided, C# performs integer division and the decimal part is removed.Relational (Comparison) Operators
Used to compare two values. These always return a boolean result (true or false).
- == (Equal to): Checks if two values are equal.
- != (Not equal to): Checks if two values are not equal.
- > (Greater than): Checks if the left value is greater than the right.
- < (Less than): Checks if the left value is less than the right.
- >= (Greater than or equal to): Checks left value is greater than or equal to the right.
- <= (Less than or equal to): Checks left value is less than or equal to the right.
Example
C#using System; int x = 5; int y = 10; Console.WriteLine(x == y); // Output: False Console.WriteLine(x != y); // Output: True Console.WriteLine(x > y); // Output: False Console.WriteLine(x < y); // Output: True Console.WriteLine(x >= 5); // Output: TrueExample: Comparison operators are commonly used when checking age, marks, salary, eligibility, or other conditions.Logical Operators
Used to combine multiple boolean conditions or expressions.
- && (Logical AND): Returns true if both statements are true.
- || (Logical OR): Returns true if at least one statement is true.
- ! (Logical NOT): Reverses the logical state (turns true to false and vice versa).
Example
C#using System; bool isSunny = true; bool isWarm = false; Console.WriteLine(isSunny && isWarm); // Output: False Console.WriteLine(isSunny || isWarm); // Output: True Console.WriteLine(!isSunny); // Output: FalseReal-World Example: Logical operators can be used to check multiple conditions, such as username/password validation or age and eligibility conditions.Assignment Operators
Used to assign values to variables. This includes compound assignments which combine arithmetic operations with an assignment.
- = (Simple Assignment): Assigns right value to left variable.
- += (Add and assign): Shorthand for x = x + y.
- -= (Subtract and assign): Shorthand for x = x - y.
- *= (Multiply and assign): Shorthand for x = x * y.
- /= (Divide and assign): Shorthand for x = x / y.
Example
C#using System; int score = 10; // Simple assignment score += 5; // Equivalent to score = score + 5; (score is now 15) score -= 2; // Equivalent to score = score - 2; (score is now 13) score *= 2; // Equivalent to score = score * 2; (score is now 26) Console.WriteLine(score); // Output: 26Increment and Decrement Operators
Unary operators used to increase or decrease a variable's value by exactly 1.
- ++ (Increment): Increases value by 1.
- -- (Decrement): Decreases value by 1.
Example
C#using System; int energy = 5; energy++; // Postfix increment (energy becomes 6) Console.WriteLine(energy); // Output: 6 --energy; // Prefix decrement (energy becomes 5) Console.WriteLine(energy); // Output: 5Note: Both++and--change the variable value by exactly one.Ternary (Conditional) Operator
A shorthand alternative to the if-else statement. It operates on three operands: condition ? expression_if_true : expression_if_false
Example
C#using System; int age = 20; string status = (age >= 18) ? "Adult" : "Minor"; Console.WriteLine(status); // Output: AdultTip: The ternary operator is useful when a simple condition needs to return one of two values.Null-Coalescing Operators
Operators designed to cleanly handle variables that might hold null values.
- ??: Returns the left-hand operand if it is not null; otherwise, it returns the right-hand operand.
- ??=: Assigns the right-hand value to the left-hand variable only if the left-hand variable is currently null.
Example
C#using System; string? name = null; // Use fallback if name is null string displayName = name ?? "Guest"; Console.WriteLine(displayName); // Output: Guest // Assign value only if null name ??= "Alice"; Console.WriteLine(name); // Output: AliceReal-World Use: Null-coalescing operators are useful when displaying default values when a database field, user input, or optional value is null.Common Mistakes to Avoid
- Do not confuse
=with==.=assigns a value, while==compares values. - Remember that integer division removes the decimal portion.
- Use parentheses when an expression needs a specific order of evaluation.
- Use logical operators carefully when combining multiple conditions.
- Use
??when you need a fallback value for a possible null value.
Real-World Example
Operators are frequently used in real applications for calculating prices, checking eligibility, validating conditions, updating counters, and handling optional values.
C#using System; int marks = 75; bool attendance = true; bool eligible = marks >= 60 && attendance; string result = eligible ? "Eligible" : "Not Eligible"; Console.WriteLine(result); // Output: EligibleSummary
C# operators are used to perform calculations, compare values, combine conditions, assign values, modify variables, select values, and handle null values. Understanding operators is essential for writing conditions, calculations, and business logic in C# applications.
Practice Questions
- Write a C# program using all arithmetic operators.
- Compare two numbers using relational operators.
- Write a program using
&&,||, and!. - Use compound assignment operators to update a variable.
- Create a program using the ternary operator to check whether a person is eligible to vote.
- Use
??to provide a default value when a variable is null.