Operators and type conversion
Operators do the maths, comparisons, null handling and bit work in C#, and type conversion moves values between types. Small rules here (int / int truncates, casts truncate, Convert rounds, Parse throws) cause many real bugs and interview questions.
6.1 Problem: 1000 / 3 = 333
C#
int bill = 1000;int friends = 3; double share = bill / friends;int left = bill % friends; Console.WriteLine($"Share: {share}");Console.WriteLine($"Left: {left}");Output
$ dotnet run bug.csShare: 333Left: 1- Step 1
1.bill / friends: both operands are int
- Step 2
2.C# does integer division: 333, decimal part cut
- Step 3
3.The division happens before the assignment
- Step 4
4.333 is stored in the double as 333
- Step 5
5.% (modulo) gives the remainder: 1
Operands decide the result type, not the variable on the left
6.2 Fix: cast first, then divide
- +, -, * work like maths; be careful only with / and %.
- Cast one operand: (double)bill / friends gives floating-point division.
- For money use decimal and round with Math.Round(value, 2).
C#
int bill = 1000;int friends = 3; double share = (double)bill / friends;decimal money = (decimal)bill / friends; Console.WriteLine(share);Console.WriteLine(money);Console.WriteLine(Math.Round(money, 2));Output
$ dotnet run fix.cs333.3333333333333333.33333333333333333333333333333.336.3 Comparison + logical operators
- >=, <=, ==, != compare values and return bool.
- || (OR): one true side is enough. && (AND): both must be true. ! (NOT) flips.
- Short circuit: in pincode != null && pincode.StartsWith("11"), the second part never runs when pincode is null.
C#
decimal cart = 650;bool isPrime = false;string? pincode = null; bool free = cart >= 499 || isPrime;bool canDeliver = pincode != null && pincode.StartsWith("11"); Console.WriteLine($"Free: {free}");Console.WriteLine($"Deliver: {canDeliver}");Console.WriteLine($"Not prime: {!isPrime}");Output
$ dotnet run logic.csFree: TrueDeliver: FalseNot prime: True6.4 Null operators: ??, ?. and ??=
| Operator | Name | Meaning |
|---|---|---|
| a ?? b | Null coalescing | a if not null, otherwise b |
| a?.B | Null conditional | null instead of a crash when a is null |
| a ??= b | Null coalescing assignment | Assign b only when a is null |
C#
string? coupon = null; string code = coupon ?? "NOCOUPON";int? length = coupon?.Length; Console.WriteLine(code);Console.WriteLine(length ?? 0); coupon ??= "WELCOME50";Console.WriteLine(coupon);Output
$ dotnet run nulls.csNOCOUPON0WELCOME506.5 Bitwise + shift: permissions
- Bitwise operators work on bits; a common use is flags/permissions.
- 1 << 1 = 2, 1 << 2 = 4 (left shift).
- | combines flags (Read | Write = 3 = binary 11); & checks if a flag is set.
C#
const int Read = 1;const int Write = 1 << 1;const int Delete = 1 << 2; int access = Read | Write; Console.WriteLine(access);Console.WriteLine($"{access:B}");Console.WriteLine((access & Write) != 0);Console.WriteLine((access & Delete) != 0);Output
$ dotnet run bits.cs311TrueFalse6.6 Overflow: checked vs unchecked
- int.MaxValue + 1 does not throw by default: it silently wraps to -2147483648 (unchecked is the default).
- checked(...) throws OverflowException instead: use it for important calculations.
C#
int views = int.MaxValue; int next = views + 1;Console.WriteLine(next); try{ int safe = checked(views + 1);}catch (OverflowException ex){ Console.WriteLine(ex.Message);}Output
$ dotnet run overflow.cs-2147483648Arithmetic operation resulted in an overflow.6.7 Type conversion: 4 tools
| Tool | Example | Behaviour |
|---|---|---|
| Implicit | long big = qty; | Automatic, only when no data can be lost (int -> long) |
| Explicit cast | (int)9.99 | Required when data can be lost; truncates (9) |
| Convert | Convert.ToInt32(9.99) | Between types; rounds (10), banker's rounding at .5; null -> 0 |
| Parse / TryParse | int.Parse("250") | string -> number |
C#
int qty = 42;long big = qty; double price = 9.99;int cast = (int)price;int converted = Convert.ToInt32(price); Console.WriteLine(big);Console.WriteLine(cast);Console.WriteLine(converted);Output
$ dotnet run cast.cs42910- Banker's rounding in Convert: 2.5 -> 2, 3.5 -> 4 (rounds to the even number at an exact half).
6.8 Parse vs Convert vs TryParse
C#
string? missing = null; int a = int.Parse("250");int b = Convert.ToInt32(missing);bool ok = int.TryParse("abc", out int c); Console.WriteLine(a);Console.WriteLine(b);Console.WriteLine(ok);Console.WriteLine(c);Output
$ dotnet run parse.cs2500False0| Method | Invalid string | null |
|---|---|---|
| int.Parse | FormatException | ArgumentNullException |
| Convert.ToInt32 | FormatException | Returns 0 |
| int.TryParse | Returns false, out value = 0 | Returns false, out value = 0 |
6.9 Common mistakes
- int.Parse on user input: "12a" throws FormatException and crashes the program. Use TryParse.
- Using & instead of && in conditions: & always evaluates both sides, so pincode.StartsWith runs on null and throws NullReferenceException.
- Dividing int by int and expecting decimals.
- Ignoring overflow in counters and totals.
C#
string input = "12a"; if (int.TryParse(input, out int qty)) Console.WriteLine($"Qty: {qty}");else Console.WriteLine("Invalid quantity"); // Invalid quantity6.10 Interview tips
- Parse throws FormatException (invalid) and ArgumentNullException (null); TryParse never throws and returns bool + out value.
- Convert.ToInt32 returns 0 for null and rounds a double; a cast truncates.
- Always use TryParse for user input: exceptions are not for normal flow.
- && / || short-circuit; & / | always evaluate both sides.
- Integer arithmetic is unchecked by default: use checked to catch overflow.