Skip to content

Operators

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).

int a = 10, b = 3;
Console.WriteLine(a % b); // 1 -- remainder
Console.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 null
Console.WriteLine(length ?? 0);
// Compound assignment
int count = 0;
count += 5; // same as count = count + 5
count *= 2; // same as count = count * 2

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 dividing
double average = (double)total / count; // 3.5, correct
  1. What does 7 / 2 evaluate to in C# when both operands are int?

    Answer3 β€” integer division truncates the fractional part, regardless of what type you assign the result to.
  2. What’s the difference between ?? and ?.?

    Answer?? (null-coalescing) provides a fallback value if the left side is null; ?. (null-conditional) safely accesses a member, short-circuiting to null instead of throwing if the object itself is null.
  3. How do you fix integer division truncation when you want a fractional result?

    AnswerCast at least one operand to a floating-point type (like double) before the division happens, e.g. (double)total / count.