Conditional branching — executing different code depending on whether a condition is true or false — is the foundation of all program logic. In C# the primary tools are the if/else statement and the ternary operator ? :. Every ASP.NET Core API controller method you write will contain conditional logic: check if the resource exists, check if the user is authorised, check if the input is valid. Writing these conditions correctly and readably is a skill you will use in every chapter of this series.
If / Else If / Else
int score = 78;
if (score >= 90)
{
Console.WriteLine("Grade: A");
}
else if (score >= 80)
{
Console.WriteLine("Grade: B");
}
else if (score >= 70)
{
Console.WriteLine("Grade: C");
}
else
{
Console.WriteLine("Grade: F");
}
// Output: Grade: C
// Single-statement bodies — braces optional but recommended
if (score >= 60)
Console.WriteLine("Pass"); // fine for very simple one-liners
else
Console.WriteLine("Fail");
// Compound conditions
bool isLoggedIn = true;
bool isAdmin = false;
if (isLoggedIn && isAdmin) // AND — both must be true
Console.WriteLine("Admin panel");
if (!isLoggedIn || !isAdmin) // OR — at least one must be true; ! = NOT
Console.WriteLine("No access to admin panel");
Note: C# evaluates compound conditions using short-circuit evaluation. For
&&, if the left operand is false, the right operand is never evaluated. For ||, if the left operand is true, the right operand is skipped. This matters when the right operand has a side effect or could throw: if (user != null && user.IsActive) — the second condition is only evaluated when user is not null, so no NullReferenceException occurs. This pattern is extremely common in C# null-safety code.Tip: Use the
is keyword for null checking in modern C# — it reads more naturally than == null and integrates with the compiler’s null-flow analysis: if (user is null) and if (user is not null). The compiler uses these patterns to understand your intent and suppress nullable warnings within the guarded block. In ASP.NET Core controllers, if (item is null) return NotFound(); is idiomatic.Warning: A common bug is assigning instead of comparing inside an
if condition. In C#, unlike C and C++, only bool expressions are valid as an if condition — if (x = 5) is a compile error because the assignment returns int, not bool. This prevents the classic “assignment instead of equality” bug. However, if (isActive = false) would compile and silently assign false to isActive — always double-check equality checks use ==.Ternary Operator
// Syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
string category = age >= 18 ? "Adult" : "Minor";
Console.WriteLine(category); // "Adult"
// Ternary in string interpolation
bool isOnline = true;
Console.WriteLine($"Status: {(isOnline ? "Online" : "Offline")}");
// Nested ternary — use sparingly, prefer if/else for readability
int score2 = 85;
string grade = score2 >= 90 ? "A"
: score2 >= 80 ? "B"
: score2 >= 70 ? "C"
: "F";
Console.WriteLine(grade); // "B"
// Common use in ASP.NET Core — returning different status codes
// return isFound ? Ok(item) : NotFound();
Null-Coalescing and Null-Conditional in Conditions
string? userName = null;
// Null-coalescing ?? — use a default when left side is null
string displayName = userName ?? "Anonymous";
Console.WriteLine(displayName); // "Anonymous"
// Null-conditional ?. — short-circuits to null if left is null
string? upper = userName?.ToUpper(); // null (no NullReferenceException)
int? len = userName?.Length; // null
// Combining with ??
string safe = userName?.Trim() ?? "Anonymous";
// Null-coalescing assignment ??= — only assign if currently null
userName ??= "Anonymous";
Console.WriteLine(userName); // "Anonymous"
Common Mistakes
Mistake 1 — Using = (assignment) instead of == (equality)
❌ Wrong — silently assigns false to the variable:
bool isActive = true;
if (isActive = false) // assigns false to isActive! always evaluates to false
DoSomething();
✅ Correct:
if (isActive == false) // or simply: if (!isActive)
Mistake 2 — Not short-circuiting null checks
❌ Wrong — throws NullReferenceException when list is null:
if (list.Count > 0 && list != null) // list.Count evaluated first — crash!
✅ Correct — null check must come first:
if (list != null && list.Count > 0) // ✓ null checked first, Count only if not null
Quick Reference — Logical Operators
| Operator | Meaning | Short-circuits |
|---|---|---|
&& |
AND — both must be true | Yes — skips right if left is false |
|| |
OR — at least one true | Yes — skips right if left is true |
! |
NOT — inverts bool | N/A |
?? |
Null-coalescing — default if null | Yes — skips right if left is not null |
?. |
Null-conditional — null if left is null | Yes — skips member access if null |
? : |
Ternary — value based on condition | Yes — only evaluates the chosen branch |