Operators
Operators
Section titled βOperatorsβWhat it means
Section titled βWhat it meansβOperators combine or compare values: arithmetic (+, -, *, /, %), comparison (==, !=, <, >=, etc.), logical (&&, ||, !), plus C#-specific ones like ?? (null-coalescing β fall back if null) and ?. (null-conditional β safely access a member that might be null).
Examples
Section titled βExamplesβint a = 10, b = 3;Console.WriteLine(a % b); // 1 -- remainderConsole.WriteLine(a / b); // 3 -- integer division, truncates!Console.WriteLine((double)a / b); // 3.333... -- cast forces floating-point division
bool isAdult = age >= 18 && hasId;bool canEnter = isAdult || hasVipPass;
string? name = GetName();string displayName = name ?? "Guest"; // fallback only if name is null
int? length = name?.Length; // null-conditional -- safely null if name is nullConsole.WriteLine(length ?? 0);
// Compound assignmentint count = 0;count += 5; // same as count = count + 5count *= 2; // same as count = count * 2Common mistake
Section titled βCommon mistakeβDividing two int values and expecting a fractional result β integer division in C# truncates toward zero, silently discarding the decimal part instead of throwing an error or rounding.
int total = 7;int count = 2;double average = total / count; // 3.0, NOT 3.5! Integer division happens BEFORE the assignment to double
// Fix: cast one operand to a floating-point type before dividingdouble average = (double)total / count; // 3.5, correctQuick practice
Section titled βQuick practiceβ-
What does
7 / 2evaluate to in C# when both operands areint?Answer
3β integer division truncates the fractional part, regardless of what type you assign the result to. -
Whatβs the difference between
??and?.?Answer
??(null-coalescing) provides a fallback value if the left side isnull;?.(null-conditional) safely accesses a member, short-circuiting tonullinstead of throwing if the object itself isnull. -
How do you fix integer division truncation when you want a fractional result?
Answer
Cast at least one operand to a floating-point type (likedouble) before the division happens, e.g.(double)total / count.