C# Operators and Expressions: Calculate and Compare Clearly
Operators combine values into calculations and conditions. Learn to read the operands, follow the grouping, distinguish assignment from comparison, and understand when a logical operator skips an unsafe operation.
What you will understand
- Identify operators, operands and expression results.
- Explain integer division, remainder and percentage calculations.
- Use precedence and parentheses to express the intended formula.
- Trace compound assignment, prefix and postfix increment.
- Choose comparisons that include the correct boundaries.
- Combine conditions with AND, OR and NOT.
- Use short-circuit guards before unsafe operations.
- Repair a calculation and verify it with changed inputs.
An operator asks a specific question about its operands
An expression combines values to produce a result. In unitPrice * quantity, * says to multiply and the two values are its operands. The result can be stored, printed or used inside another expression. Start by asking what each value means and what result the operation should produce.
An assignment such as total = subtotal + delivery computes the right side and then stores its result in total. It is not an algebraic promise that total will automatically track future changes to subtotal. If a source value changes, a previously calculated result stays unchanged until you assign it again.
You will use variables, numeric types and conversions from earlier lessons. Predict each example before running it. The programs have fixed inputs so you can concentrate on the operators; edit those values to test your reasoning. One example deliberately fails at runtime to show why short-circuit evaluation matters.
Program.cs · Calculate with named operands
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Subtotal: 37.50
Total: 41.50
In unitPrice * quantity, the two values are operands and * is the multiplication operator. The product becomes subtotal. A later addition combines subtotal and delivery. Naming the intermediate result makes the calculation easier to check than hiding every operation inside one long output expression.
Arithmetic depends on both the symbol and the operand types
Use + to add, - to subtract, * to multiply, / to divide and % to calculate a remainder. A symbol is not enough to predict every result: the operand types matter. Integer division and fractional division can produce different answers from values that look similar on paper.
For positive integer counts, quotient and remainder help explain complete groups and leftovers. Seventeen items packed five per box make three complete groups with two left over. The remainder is not a percentage. To calculate a percentage amount, multiply a value by an explicitly chosen rate.
Integer division discards the fractional part toward zero. A nonzero integer remainder has the sign of the left operand. Zero divisors are invalid for integer division and remainder; a runtime operation throws. Floating-point special values and decimal arithmetic have their own rules, so do not generalize every integer rule to every numeric type.
Program.cs · Compare the arithmetic operators
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Sum: 22
Difference: 12
Product: 85
Whole quotient: 3
Remainder: 2
Seventeen contains three whole groups of five with two left over. / returns the quotient for these integer operands, while % returns the remainder. % is not a percentage operator. A percentage such as ten percent is represented by multiplication by 0.10 in an appropriate numeric type.
Program.cs · Operand types determine division
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Integer: 3
Fractional: 3.5
Negative quotient: -3
Negative remainder: -1
Integer division truncates toward zero. For a nonzero integer remainder, its sign follows the left operand, so -7 % 2 is -1. Convert an operand before dividing when the fraction matters. The type of a destination variable alone cannot restore a fraction already discarded by the operation.
Use parentheses to express the intended calculation
Precedence determines how operators group when parentheses do not say otherwise. Multiplication, division and remainder bind more tightly than addition and subtraction. Operators such as multiplication and division at the same precedence level group left to right in the examples below.
Parentheses change grouping or make it clearer to a reader. Compare 2 + 3 * 4 with (2 + 3) * 4: the first asks for two plus a product, while the second asks for a product of a sum. Neither formula is automatically more correct; only one may match the intended problem.
Do not confuse precedence with a rule that all high-precedence operands are evaluated first. C# evaluates operands from left to right, with conditional operators able to skip some operands. For beginner calculations, keep state changes out of complex expressions and name intermediate results instead of relying on clever ordering.
Program.cs · Grouping changes which calculation you express
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
14
20
8
2
Multiplication binds more tightly than addition, so the first expression is 2 + 12. Parentheses make the sum happen before multiplication in the second expression. Multiplication and division have the same precedence and group left to right: 20 / 5 * 2 means (20 / 5) * 2, not 20 / (5 * 2).
Assignment updates state; a calculation alone does not
The = operator stores a value. Compound assignments such as +=, -=, *=, /= and %= combine an operation with storing its result. For the simple int variable below, stock += 5 has the same numeric effect as stock = stock + 5. More advanced expressions and conversions require additional care, so this is not a universal textual substitution rule.
Increment and decrement add or subtract one. A standalone count++ is a compact update. When an increment is used inside another expression, prefix and postfix differ in the value they produce for that expression even though both change the variable.
Avoid packing several updates into one expression merely because the language permits it. The goal is to understand which values exist at each step. Trace the initial value, the expression result and the stored value separately. Output labels below make those three stages visible.
Program.cs · Store an updated value explicitly
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
After sale: 17
After delivery: 22
After correction: 44
For this simple int variable, stock -= 3 updates stock using its current value minus three. Likewise += and *= update it using addition and multiplication. The last step is an illustrative correction, not a real inventory policy. An expression such as stock - 3 by itself does not assign a new stock value.
Program.cs · Separate the expression result from the updated variable
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Postfix result: 3
Count now: 4
Prefix result: 5
Count finally: 5
After decrement: 4
Both ++ forms increment the variable. Postfix count++ produces the previous value as the expression result; prefix ++count produces the updated value. A standalone count++ and ++count have the same final effect on count. Prefer separate statements when combining updates would make an expression hard to explain.
Compare values to produce true or false
Comparison operators answer questions. == checks equality, != checks inequality, and <, <=, > and >= compare order. These numeric comparisons produce bool values. A result of true says the condition holds for the current operands, not that the application has performed an action.
Boundary wording matters. If requested items may equal the available stock, requested <= available expresses that rule. Using < excludes the exact-stock case. Test equal values, one smaller and one larger so that an off-by-one error is easy to detect.
Assignment and equality have different roles: = stores, == compares. Also avoid mathematical shorthand such as 1 <= quantity <= 6; C# does not interpret it as a chained range condition. Write quantity >= 1 && quantity <= 6 so both Boolean comparisons are explicit.
Program.cs · Comparisons produce Boolean values
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Equal: True
Different: False
Less: False
Fits: True
Greater: False
At least: True
Equality matters at the boundary: six requested items fit when six are available, so <= is appropriate for that question. The comparison returns bool. It does not reserve inventory or change either operand. Use == to compare and = to assign; their different purposes are not interchangeable.
Combine conditions without losing the meaning of the rule
Use && when all requirements must hold and || when at least one alternative is sufficient. Inclusive OR also allows both conditions to be true. Prefix ! reverses a Boolean result. Choose names such as gateOpen or quantityAllowed so that reading the expression aloud reveals the policy.
Grouping is especially valuable when combining AND and OR. && binds more tightly than ||, so a || b && c groups as a || (b && c). If your rule means (a || b) && c, write those parentheses. Small changes can alter who or what passes a condition.
Negation also has a scope. !member || coupon is different from !(member || coupon). In the first expression, only member is negated; in the second, the whole combined answer is reversed. Break a complex policy into named intermediate Boolean values before adding another operator.
Program.cs · Combine requirements and alternatives
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Normal entry: False
Entry allowed: True
Gate closed: True
&& requires both conditions. || requires at least one, including the case where both are true. ! negates one Boolean value. This example deliberately gives a staff override precedence as a policy decision through named intermediate values; a real permission system must decide and enforce its own trusted rules.
A protective check must run before the risky operation
With &&, a false left operand already determines a false result, so the right operand is skipped. With ||, a true left operand already determines a true result, so the right operand is skipped. This behavior is called short-circuit evaluation.
Ordering makes a guard useful. Check count != 0 before total / count, or check whether a string is null before reading its Length. A condition evaluated after an unsafe operation cannot protect that operation retroactively. The skipped side must also not be relied on for a required side effect.
For Boolean operands, single & and | evaluate both sides. They can produce the same truth value as their conditional counterparts when all operands safely evaluate, but their execution behavior differs. The deliberate failure below shows why replacing && with & is not a harmless spelling change.
Program.cs · Guard an integer division with AND
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Large average: False
The left side is false, which already determines an AND result. && skips the right operand, so division by zero is never attempted. The guard must come first. This expression uses integer division; its purpose is to demonstrate evaluation, not to calculate a precise fractional average.
Program.cs · A single ampersand evaluates both Boolean operands
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Checking average
Then execution fails with DivideByZeroException.For these Boolean operands, & computes AND but evaluates both sides. It therefore reaches the forbidden division even though the left condition is false. The matching short-circuit form is &&. The bitwise uses of & with integers are a separate topic.
Program.cs · Use OR when the first condition already proves failure
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Missing or short: True
The null test is true, so || does not evaluate name.Length. This avoids accessing a property on null. With a present name, the second condition is evaluated. Reversing the operands would remove this protection; a guard must be evaluated before the operation it protects.
The same plus symbol can mean text concatenation
When a + operation has a string operand, it can join text rather than add numbers. Because addition and concatenation group left to right in these expressions, a label added first can turn later numbers into appended text. The output may look like a number while being the wrong calculation.
Use parentheses to complete numeric arithmetic before joining a label, or put the numeric expression inside interpolation braces. The distinction is about operand types and grouping, not about how persuasive the final label looks.
Before the repair and lab, pause and describe each result in words: an amount, a count or a Boolean decision. Then identify the expression that computes it. A program can compile and run while answering a different question from the one the reader intended.
Program.cs · The plus operator can concatenate strings
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Total: 23
Total: 5
Total: 5
The first + already has a string operand, so it produces text Total: 2. Adding second then appends 3 to that text. Parentheses perform numeric addition first in the second line. Interpolation makes the intended numeric expression clear in the third line.
Guided repair: a rate is not a discount amount
A ten-percent discount on a subtotal of 30 should leave 27. The program subtracts only 0.10 instead. Trace what each operand represents and repair the expression using named intermediate amounts.
Program.cs · Repair the grouping of a discount
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Discounted subtotal: 29.90
The code subtracts a fixed amount of 0.10, not ten percent of the subtotal. The bug is a mismatch between the intended quantity and the expression, rather than a syntax error. Work out the discount amount separately before choosing how to subtract it.
Repair checkpoints
- Explain why the broken version prints 29.90.
- Keep discountRate as a decimal rate of 0.10m.
- Calculate subtotal, then discount amount, then discounted subtotal.
- With rate 0m, expect 30.00; with 0.25m, expect 22.50.
- With quantity 0, expect 0.00 under these fixed-input assumptions.
Reveal the repair and explanation
Program.cs · Name the subtotal and discount amount
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Discounted subtotal: 27.00
A rate is not an amount. Multiplying the subtotal of 30 by the rate 0.10 produces a discount amount of 3. Subtracting that amount leaves 27. Naming the stages exposes both the units and the reasoning. This fixed-input report does not define a complete pricing or currency-rounding policy.
Independent lab: repair a basket summary
Repair a basket report so its expressions match three independent requirements: add delivery once, allow a positive requested count up to available stock, and mark eligibility when membership or a coupon is present.
Acceptance checklist
- Use unitPrice 12.50m, quantity 4, delivery 5m and stock 4.
- Calculate subtotal by multiplication, then add delivery once.
- Require quantity > 0 and quantity <= stock for canFulfil.
- Set eligible when member or coupon is true, including when both are true.
- Print Total: 55.00, Can fulfil: True and Discount eligible: True for the reference values.
- Report eligibility only; do not apply a discount or claim to reserve stock.
Program.cs · Basket summary starter
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Total: 112.50
Can fulfil: False
Discount eligible: False
Three expressions disagree with the lab requirements: delivery has been multiplied by the unit price, exact available stock has been excluded, and two alternative eligibility routes have been treated as simultaneous requirements. Each expression compiles; understanding the intended question is essential.
Show hints
- A delivery amount is money to add after multiplication, not another item count.
- The exact-stock case needs <= rather than <.
- Use && for simultaneous requirements and || for alternative routes.
Reveal the reference solution
Program.cs · Basket summary reference solution
Predict the result, edit Program.cs, then run your program.
Standard input · optional
Select Run code to compile and execute this program.
Total: 55.00
Can fulfil: True
Discount eligible: True
Delivery is added once after item multiplication. The fulfilment expression requires a positive count and allows equality at the stock boundary. Either membership or a coupon makes this illustrative flag true. Eligibility is reported only: no discount is applied to total, and no inventory or payment action occurs.
Changed-input checks
- Quantity 1 with stock 4: total 17.50 and fulfilment True.
- Quantity 4 with stock 4 succeeds; quantity 5 fails fulfilment.
- Quantity 0 fails fulfilment; the illustrative formula still reports the delivery amount.
- Member false and coupon true is eligible; both false is not.
- Both flags true is still eligible because OR is inclusive.
Recap: read the operator and the operands
Use these operator groups as a reading guide. Check operand types, grouping, state changes and whether either side of a condition is skipped.
+ - * / %- Calculate with numeric values; types affect division and other behavior.
= and +=- Assign a value or update a simple variable with an operation.
++ and --- Add or subtract one; prefix and postfix produce different expression results.
== != < <= > >=- Compare values and produce bool results.
&&- Require both conditions; skip the right operand if the left is false.
||- Accept at least one condition; skip the right operand if the left is true.
!condition- Negate the condition; parentheses determine how much is negated.
(expression)- Make the intended grouping explicit; a final conversion cannot undo an earlier loss.
Frequently asked questions
Does % mean percent?
No. For these integers it returns the remainder after division. Calculate a percentage amount by multiplying a value by a rate, such as subtotal * 0.10m.
Why does 7 / 2 give 3?
Both operands are int, so integer division truncates toward zero. Convert an operand before dividing when you need a fractional result.
Are = and == interchangeable?
No. = assigns a value; == compares values. For a Boolean variable, assignment can itself be used as an expression, so using the wrong operator can sometimes compile and still change the program incorrectly.
Should I use & instead of &&?
For Boolean conditions, && skips an unnecessary right operand, while & evaluates both. Use a short-circuit guard when the right operand would be invalid without the left check.
Does ++ always return the updated value?
Prefix ++count produces the updated value, while postfix count++ produces the previous value. Both still increment the variable. As separate statements their final effect is the same.
Why use intermediate variables instead of one formula?
A name such as subtotal or discount identifies what an intermediate value means. This makes grouping, units and boundary tests easier to inspect. Short expressions remain useful when their meaning is clear.
Can you trace the expression?
Trace arithmetic, assignments, comparisons and short-circuit conditions. Read the explanation after each answer.
Next step and references
An expression answers a question using values and operators. Types affect arithmetic, grouping expresses the formula, and logical conditions can skip an unsafe right operand. Test boundary values and keep state changes clear.
Next is C# Math and Numeric Decisions. You will use library helpers for rounding, bounds and other numeric calculations while checking the meaning of each result.
Official references
Original SovranCode explanations, examples and exercises. Technical details were checked against these references.
- Microsoft Learn: Arithmetic operators
- Microsoft Learn: Boolean logical operators
- Microsoft Learn: Operators and expressions
Last updated: .