Lesson 6 — Operations

Operators

C# operators build on the Java foundation and add null-specific operators that make working with nullable data safer and more concise.

CSHARP — Arithmetic
int a = 17, b = 5;
Console.WriteLine(a + b);   // 22
Console.WriteLine(a - b);   // 12
Console.WriteLine(a * b);   // 85
Console.WriteLine(a / b);   // 3  (integer division!)
Console.WriteLine(a % b);   // 2  (remainder)

// To get decimal division:
Console.WriteLine((double)a / b);  // 3.4

// Compound assignment:
int score = 50;
score += 10; // 60
score -= 5;  // 55
score *= 2;  // 110
Console.WriteLine(score);

Null-Coalescing and Null-Conditional

These operators, unique to C#, make null-handling elegant and safe without verbose null checks.

CSHARP — Null operators
string? city = null;

// ?? — return left if not null, else right:
string display = city ?? "Unknown";
Console.WriteLine(display); // Unknown

// ??= — assign right only if left is null:
city ??= "Johannesburg";
Console.WriteLine(city); // Johannesburg

// ?. — null-conditional: call member only if not null:
string? name = null;
int? length = name?.Length;  // null (no NullReferenceException)
Console.WriteLine(length ?? 0); // 0

// Chain ?. operators:
string? upper = name?.ToUpper()?.Trim();
Console.WriteLine(upper ?? "(no name)");

Comparison and Logical Operators

CSHARP — Comparison and logical
int mark = 74;
bool hasSubmitted = true;

// Comparison:
Console.WriteLine(mark >= 50);  // True
Console.WriteLine(mark != 100); // True

// Logical (&&, ||, !):
if (mark >= 50 && hasSubmitted)
    Console.WriteLine("Competent and submitted.");

// Short-circuit: right side not evaluated if left decides outcome
bool result = (mark > 0) || HeavyComputation(); // skips HeavyComputation

// Ternary:
string grade = mark >= 50 ? "Pass" : "Fail";
Console.WriteLine(grade);

Practice Task

Your Turn

Given nullable learner name and nullable mark: use ?? to print "Anonymous" if name is null and 0 if mark is null. Use ?. to safely get the name length. Divide 100 by 7 as both int and double — explain the difference with a comment.

Common Mistakes

  • Integer division: 7 / 2 == 3 not 3.5 — cast one operand to double first.
  • ?? requires a nullable or reference type on the left side.
  • = instead of == in conditions.
  • Missing ? when declaring nullable — string name = null is a warning in C# 8+ with nullable enabled.

Professional Tip

Use ?? to replace verbose null checks in one expression. It reads naturally: 'use city, or if city is null, use Unknown'.

Mini Quiz

What does the ?? operator do?