Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 182 ยท Operators and Control Flow

Operators

Learn every everyday C# operator - arithmetic, comparison, short-circuit logic, bitwise and shift (including >>>), compound assignment, ++ and --, the ternary operator and precedence.

Variables hold data; operators do something with it. Every +, ==, && and = in your code is an operator, and C# has around fifty of them. Most are familiar from maths, but a handful behave in ways that surprise people coming from other languages: integer division throws away the remainder, % can return a negative number, i++ and ++i differ, and a + b * c does not mean (a + b) * c.

This lesson walks through the operators you use daily, in groups: arithmetic, comparison, logical, bitwise and shift, assignment, increment and decrement, the conditional (ternary) operator, and finally the precedence rules that decide which operator runs first. Along the way you'll meet the C# 11 unsigned right shift >>> and checked arithmetic. If you need a refresher on the types these work on, see Integer Types and Floating-Point and decimal.

Arithmetic operators

Operator Meaning Example Result
+ addition (also string concatenation) 7 + 2 9
- subtraction, or negation when unary 7 - 2 5
* multiplication 7 * 2 14
/ division 7 / 2 3
% remainder (modulus) 7 % 2 1

The rule that trips up beginners: when both operands are integers, / is integer division and the fraction is thrown away (it truncates toward zero). To get 3.5, at least one operand must be floating-point.

C# Arithmetic and integer division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last three lines show why parentheses matter with +: evaluation goes left to right, and once a string is involved, everything after it is text. Prefer string interpolation ($"Total: {1 + 2}") which avoids the issue entirely (see Console Output and Formatting).

Dividing an integer by zero throws DivideByZeroException; dividing a floating-point number by zero gives Infinity or NaN. Integer / also throws OverflowException for int.MinValue / -1, because the result doesn't fit.

Overflow and checked

Integer arithmetic is unchecked by default: when a result doesn't fit, it silently wraps around, as if the number line were a circle. Use checked to get an OverflowException instead.

C# Wrap-around versus checked

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The fix for a * b is to widen before multiplying: (long)a * b. Writing (long)(a * b) is useless because the overflow has already happened inside the int multiplication. Since C# 11 a type can also define its own checked operator versions (for example checked operator +), which is how types such as Int128 and BigInteger-like structs support checked; you'll see this in the Advanced C# chapter.

Comparison operators

Comparison operators produce a bool: ==, !=, <, >, <=, >=.

C# Comparison operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

== on strings compares the characters, because string overloads the operator. Collections do not, so list1 == list2 compares identity. Records (see the Classes chapter) compare their values. The is patterns on the last line are the subject of Pattern Matching Basics.

Logical operators

We met these in bool and char. To recap: ! (not), && (and), || (or) with short-circuit evaluation, &, |, ^ without it. Because && is evaluated before ||, mixed conditions need parentheses to be readable:

C# Combining conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Bitwise and shift operators

Bitwise operators work on the individual bits of integers. They look like the logical ones, but apply to every bit position:

Operator Name 0b1100 and 0b1010 give
& AND 0b1000
| OR 0b1110
^ XOR 0b0110
~ complement (flip all bits) ~0b1100 flips every bit
<< shift left multiplies by 2 per step
>> shift right divides by 2 per step, keeps the sign
>>> unsigned shift right (C# 11) divides by 2 per step, fills with zeros
C# Bits and shifts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Shifting left by n multiplies by 2n and shifting right divides, which is how hash functions, graphics code and binary file formats pack data. >>> (new in C# 11) is the unsigned right shift: for a negative int, >> keeps the sign bit (so -16 >> 2 is -4), while >>> always shifts in zeros and so treats the bit pattern as unsigned. On uint and other unsigned types both operators behave the same.

The same operators on enums are how [Flags] works (see Enums and Flags). For byte and short, operands are promoted to int first, so ~b or b << 1 give an int you must cast back to a byte.

Assignment and compound assignment

The simple assignment operator = stores a value and also produces that value, so you can chain it. A compound operator combines an operation with assignment: x += 3 means x = x + 3 (with x evaluated only once). Every arithmetic, bitwise and shift operator has one, plus ??= for null defaults.

C# Compound assignment

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice small += 100 compiles even though small = small + 100 does not: the compound form hides an explicit cast, and in unchecked code that means a silent wrap. This is another reason to be thoughtful with small integer types.

Increment and decrement

++ adds one and -- subtracts one. Each comes in two forms:

  • Postfix i++: the expression's value is the old value; the variable changes afterward.
  • Prefix ++i: the variable changes first, and the expression's value is the new value.

When used as a standalone statement the two are identical. The difference only matters inside a larger expression, where it is often clearer to split the code into separate lines.

C# Prefix versus postfix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Write i++ as its own statement, and avoid using the value of i++ or ++i inside other expressions. Code like k++ + k++ is legal and well defined (left to right), but a reader has to stop and simulate it.

The conditional (ternary) operator

condition ? whenTrue : whenFalse is an expression that picks one of two values. Both branches must have a compatible type. It is the right tool for small choices, and the wrong one for nested logic.

C# The ternary operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The conditional operator can also produce references (ref var target = ref (flag ? ref a : ref b);), an advanced feature we'll meet with ref locals in Parameters: ref, out, in and params. For flow decisions with statements inside, use if, else if and else.

Operator precedence

When an expression has several operators, precedence decides which runs first and associativity breaks ties. From highest to lowest (the groups you need most):

Level Operators Associativity
1. Primary x.y, f(x), a[i], x?.y, x++, x--, new, typeof, checked left
2. Unary +x, -x, !x, ~x, ++x, --x, (T)x right
3. Multiplicative *, /, % left
4. Additive +, - left
5. Shift <<, >>, >>> left
6. Relational <, >, <=, >=, is, as left
7. Equality ==, != left
8. Bitwise AND & left
9. Bitwise XOR ^ left
10. Bitwise OR | left
11. Logical AND && left
12. Logical OR || left
13. Null-coalescing ?? right
14. Conditional ?: right
15. Assignment, lambda =, +=, ??=, => right
C# Precedence in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The famous trap is the one commented out: in C#, & has lower precedence than !=, so flags & 0b0100 != 0 does not compile (error CS0019: Operator '&' cannot be applied to operands of type 'int' and 'bool'). Always parenthesize bit tests. In general, add parentheses whenever you mix more than two kinds of operators; the cost is zero and the readers thank you.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does -7 % 3 evaluate to in C#?

    The remainder takes the sign of the left operand. -7 / 3 truncates to -2, and -7 - (-2 * 3) = -1.
  2. 2. What is 7 / 2 when both operands are int?

    Integer division discards the fraction (it truncates toward zero). Make one operand a double, such as 7 / 2.0, to get 3.5.
  3. 3. After int i = 5; int a = i++;, what are a and i?

    Postfix i++ yields the old value (5) and then increments i to 6. Prefix ++i would give a = 6.
  4. 4. What does -16 >>> 2 do differently from -16 >> 2 on an int?

    >> is an arithmetic shift that copies the sign bit. >>> (C# 11) is an unsigned shift that fills with zeros, so -16 >>> 2 is 1073741820.
  5. 5. Why does if (flags & 4 != 0) not compile?

    Equality binds tighter than bitwise AND, so 4 != 0 is evaluated first and yields a bool, which cannot be ANDed with an int. Write (flags & 4) != 0.

Summary

  • Integer / truncates toward zero, % takes the sign of the left operand; floating-point division by zero gives Infinity/NaN, integer division by zero throws.
  • Integer overflow wraps silently unless the code is checked; widen an operand ((long)a * b) before multiplying to avoid overflow in intermediate results.
  • == compares values for numbers and strings but references for most classes; compare floating-point numbers with a tolerance.
  • && and || short-circuit and && binds tighter than ||; use parentheses for mixed conditions.
  • Bitwise & | ^ ~ and shifts << >> >>> work on bits; >>> (C# 11) shifts in zeros regardless of the sign.
  • Compound assignment (+=, <<=, ??=) includes an implicit cast back to the left type; i++ yields the old value, ++i the new one.
  • condition ? a : b is an expression for simple choices; use switch expressions for many outcomes.
  • Precedence follows the table above; parenthesize bit tests ((flags & mask) != 0) and any mix of operator kinds.

Next: if, else if and else