04. Operators and Expressions in C#
Level: Beginner
- What operators are
- Calculate total marks and percentage
- Compare marks to decide pass or fail
- Use logical operators for eligibility checks
- Update values using assignment operators
- Use ternary operator for simple results
- Avoid common operator mistakes
In the previous article, you learned variables.
Variables store data. Operators help us work with that data.
Example:
int total = maths + science;
bool hasPassed = percentage >= 35;
Here:
+adds values>=compares values
These symbols are called operators.
The Problem: How Do We Calculate Student Results?
In a School Management System, we need to calculate:
- Total marks
- Percentage
- Pass or fail
- Fee balance
- Exam eligibility
Example:
Maths: 90
Science: 80
English: 70
Total = 240
Percentage = 80
Result = Pass
Operators help us do these calculations.
What is an Operator?
An operator is a symbol that performs an action.
int total = 90 + 80;
| Part | Meaning |
|---|---|
90 | First value |
+ | Operator |
80 | Second value |
total | Variable storing result |
Common Operator Types
| Type | Operators | Use |
|---|---|---|
| Arithmetic | +, -, *, /, % | Calculations |
| Comparison | ==, !=, >, <, >=, <= | Check values |
| Logical | &&, ` | |
| Assignment | =, +=, -=, *=, /= | Store/update values |
| Ternary | ? : | Simple if/else in one line |
| Null-safe | ??, ?. | Handle missing values safely |
Quick Definitions
- Operator - Symbol that performs an action on values
- Arithmetic - Operators for calculations (
+,-,*,/) - Comparison - Operators for checking values (
>,==,!=) - Logical - Operators for combining conditions (
&&,||,!) - Assignment - Operators for storing or updating values (
=,+=,-=) - Type Casting - Converting one data type to another
- Operator Precedence - Order in which operations happen
Important: Integer Division
When you divide two integers, C# drops the decimal part.
int result = 10 / 3; // 3 (not 3.333)
double result2 = 10.0 / 3; // 3.333 (decimal numbers)
This matters for marks and fees calculations.
Use double when you need accurate decimal results.
For percentage from integers:
int total = 424;
// Wrong: both are integers
double percentage = total / 500 * 100; // gives 0
// Correct: convert to double first
double percentage = (double)total / 500 * 100; // gives 84.8
Step 1: Arithmetic Operators
Arithmetic operators are used for calculations.
| Operator | Meaning | Example |
|---|---|---|
+ | Add | 10 + 5 |
- | Subtract | 10 - 5 |
* | Multiply | 10 * 5 |
/ | Divide | 10 / 5 |
% | Remainder | 10 % 3 |
Example:
int maths = 90;
int science = 80;
int english = 70;
int total = maths + science + english;
double percentage = (double)total / 300 * 100;
Console.WriteLine($"Total: {total}");
Console.WriteLine($"Percentage: {percentage}");
Why (double) Casting is Needed
Problem: If both numbers are integers, the result is an integer (decimal part lost).
int total = 424;
int maxMarks = 500;
// Wrong: both integers, 424 / 500 = 0 (integer division)
double percentage = total / maxMarks * 100; // gives 0
// Correct: convert total to double first
double percentage = (double)total / maxMarks * 100; // gives 84.8
Beginner rule: For percentage or average from integers, use (double) casting on the first number.
This tells C#: "Treat this as a decimal number, not an integer."
Another way (also correct):
double percentage = total / 500.0 * 100; // 500.0 is double
Step 2: Fee Calculation
Use decimal for money.
decimal totalFees = 30000.00m;
decimal paidAmount = 18000.00m;
decimal balance = totalFees - paidAmount;
Console.WriteLine($"Balance Fees: {balance}");
Output:
Balance Fees: 12000.00
Step 3: Comparison Operators
Comparison operators return true or false.
| Operator | Meaning | Example |
|---|---|---|
== | Equal to | marks == 100 |
!= | Not equal to | marks != 0 |
> | Greater than | marks > 35 |
< | Less than | marks < 35 |
>= | Greater than or equal | marks >= 35 |
<= | Less than or equal | marks <= 100 |
Example:
double percentage = 80;
bool hasPassed = percentage >= 35;
bool hasDistinction = percentage >= 75;
bool isFullMarks = percentage == 100;
Console.WriteLine($"Passed: {hasPassed}");
Console.WriteLine($"Distinction: {hasDistinction}");
Console.WriteLine($"Full Marks: {isFullMarks}");
Step 4: Logical Operators
Logical operators combine multiple true or false values.
| Operator | Meaning | Example |
|---|---|---|
&& | AND - both must be true | hasPaidFees && hasAttendance |
| ` | ` | |
! | NOT - reverse value | !hasPaidFees |
Example:
bool hasPaidFees = true;
bool hasAttendance = true;
bool hasPassedExam = false;
bool canWriteExam = hasPaidFees && hasAttendance;
bool canGetCertificate = hasPaidFees && hasAttendance && hasPassedExam;
bool isBlocked = !hasPaidFees;
Console.WriteLine($"Can write exam: {canWriteExam}");
Console.WriteLine($"Can get certificate: {canGetCertificate}");
Console.WriteLine($"Blocked: {isBlocked}");
Step 5: Assignment Operators
Assignment means storing or updating a value.
| Operator | Meaning | Same As |
|---|---|---|
= | Assign | x = 10 |
+= | Add and assign | x = x + 5 |
-= | Subtract and assign | x = x - 5 |
*= | Multiply and assign | x = x * 2 |
/= | Divide and assign | x = x / 2 |
Example:
decimal balance = 30000.00m;
balance -= 10000.00m; // paid 10000
balance += 500.00m; // late fee added
Console.WriteLine($"Final Balance: {balance}");
Step 6: Increment and Decrement
Use ++ to add 1.
Use -- to subtract 1.
int presentDays = 20;
presentDays++;
Console.WriteLine(presentDays); // 21
presentDays--;
Console.WriteLine(presentDays); // 20
Use this later in loops and counters.
Step 7: Ternary Operator
Ternary operator is a short way to write simple if/else.
Syntax:
condition ? valueIfTrue : valueIfFalse
Example:
double percentage = 80;
string result = percentage >= 35 ? "Pass" : "Fail";
Console.WriteLine(result);
Use ternary only for simple decisions.
For complex logic, use if/else in the next article.
Step 8: Null-Safe Operators
Operators ?? (null coalescing) and ?. (null-conditional) handle missing data.
You'll learn about null values in detail in Article 23: Nullable Types.
For now, focus on arithmetic, comparison, and logical operators. Come back to this section after you understand null values.
Full Example: Student Result Calculator
Expected output:
=== Sahasra Academy ===
=== Student Result ===
Name: Arjun Reddy
Total Marks: 424/500
Percentage: 84.80
Result: Pass
Distinction: Yes
Balance Fees: 10000.00
Operator Precedence (Order Matters)
Operator precedence means: some operators run before others.
Example:
int result = 10 + 5 * 3;
Question: Is the answer 45 or 25?
10 + 5 = 15, then 15 * 3 = 45 // Wrong
10 + (5 * 3) = 10 + 15 = 25 // Correct
Why? Multiplication happens before addition.
To force different order, use parentheses:
int result1 = 10 + 5 * 3; // 25 (multiply first)
int result2 = (10 + 5) * 3; // 45 (parentheses first)
Beginner rule: When in doubt, use parentheses. It makes code clear.
For marks and fees:
double percentage = (double)total / maxMarks * 100;
// Parentheses make it clear:
// 1. Convert total to double
// 2. Divide by maxMarks
// 3. Multiply by 100
Quick Reference
| Need | Example |
|---|---|
| Add marks | total = maths + science |
| Calculate balance | balance = totalFees - paidAmount |
| Check pass | percentage >= 35 |
| Check both conditions | hasPaidFees && hasAttendance |
| Check either condition | `isTeacher |
| Reverse condition | !hasPaidFees |
| Add late fee | balance += 500 |
| Simple result text | marks >= 35 ? "Pass" : "Fail" |
| Default for null later | phone ?? "Not Provided" |
When You'll Use This in SMS
Operators are core to SMS calculations.
Student marks calculation:
- Total:
english + maths + science + social + language - Percentage:
(double)totalMarks / 500 * 100 - Pass/Fail:
percentage >= 35
Fee calculation:
- Balance:
totalFees - paidAmount - With late fee:
balance += 500 - Fully paid:
balance == 0
Eligibility check:
- Can write exam:
hasPaidFees && hasAttendance - Can get certificate:
hasPaidFees && hasAttendance && hasPassedExam
Real impact:
- Wrong operators = wrong calculations
- Wrong data types = lost money (use
decimal) - Right operators = reliable SMS for thousands of students
Common Mistakes (3 Critical)
Mistake 1: Using = instead of ==
Wrong:
if (marks = 100)
{
}
Correct:
if (marks == 100)
{
}
Meaning:
= assigns value
== compares value
Mistake 2: Integer division
Wrong:
int total = 424;
double percentage = total / 500 * 100;
Result: Wrong. Both are integers.
Correct:
double percentage = (double)total / 500 * 100;
Mistake 3: Forgetting parentheses
Wrong:
int result = 10 + 5 * 3; // 25, not 45
Correct if you want 45:
int result = (10 + 5) * 3;
Try This Now
Run the result calculator example above. Then experiment:
- Change marks values: english=90, maths=92, science=88, social=86, language=89
- Run and see new percentage
- Change balanceFees values: what if paid amount is 25000 instead of 20000?
- Change totalFees: what if fees were Rs. 40000 instead of Rs. 30000?
See how operators calculate different results based on input values.
C# operators video coming soon on NexCoding YouTube. Subscribe for updates.
Best Practices
- Use parentheses for clear calculations.
- Use
decimalfor money calculations. - Use
(double)when calculating percentage from integers. - Use
==for comparison, not=. - Use
&&when all conditions must be true. - Use
||when any one condition can be true. - Use ternary only for simple one-line decisions.
Practice Task
Create a program for fee calculation:
Student Name: Priya Sharma
Total Fees: 40000.00
Paid Amount: 25000.00
Late Fee: 500.00
Calculate:
- Balance fees
- Final balance after adding late fee
- Whether payment is complete
Expected starter:
string studentName = "Priya Sharma";
decimal totalFees = 40000.00m;
decimal paidAmount = 25000.00m;
decimal lateFee = 500.00m;
decimal balance = totalFees - paidAmount;
balance += lateFee;
bool isFullyPaid = balance == 0;
Console.WriteLine($"Student: {studentName}");
Console.WriteLine($"Final Balance: {balance}");
Console.WriteLine($"Fully Paid: {isFullyPaid}");
Quick Revision
| Question | Answer |
|---|---|
| Which operator adds values? | + |
| Which operator compares equality? | == |
| Which operator assigns value? | = |
| Which operator means AND? | && |
| Which operator means OR? | ` |
| Which operator gives default for null later? | ?? |
| Which operator is used for simple if/else? | ? : |
An operator is a symbol that performs an action on values.
Example:
int total = 50 + 40;
bool passed = total >= 35;
Here, + adds values and >= compares values.
= is assignment. It stores a value.
== is comparison. It checks whether two values are equal.
Example:
int marks = 100; // assignment
bool full = marks == 100; // comparison
Integer division happens when both values are integers.
Example:
int result = 10 / 3; // 3
The decimal part is removed.
Use double when you need decimal result:
double result = 10.0 / 3;
&& means AND. All conditions must be true.
|| means OR. Any one condition can be true.
Example:
bool canWriteExam = hasPaidFees && hasAttendance;
bool canEnterCampus = isStudent || isTeacher;
The ternary operator is a short way to return one of two values based on a condition.
Example:
string result = marks >= 35 ? "Pass" : "Fail";
Use it only for simple conditions.
The null coalescing operator ?? gives a default value when the left side is null.
Example:
string? phone = null;
string display = phone ?? "Not Provided";
Here, display becomes "Not Provided".
Use ChatGPT, Claude, or Copilot to go deeper on C# operators. Try these prompts:
"Explain C# operators using student marks and fee examples""Give me 10 practice questions for arithmetic, comparison, and logical operators""Explain the difference between = and == with examples""Quiz me with 5 beginner questions about C# operators"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.