Roadmap › C# Language — Basics to Advanced › Module: Getting Started
Lessons in this course (38)

6. Conditions and loops: if, ternary, switch, for, while, do-while

Basic★ Must knowLesson 6 of 38

if / else if / else and the ternary operator:

csharp
if (marks >= 75) Console.WriteLine("Distinction");
else if (marks >= 35) Console.WriteLine("Pass");
else Console.WriteLine("Fail");

string result = marks >= 35 ? "Pass" : "Fail";           // ternary: condition ? whenTrue : whenFalse
string label = marks >= 75 ? "A" : marks >= 35 ? "B" : "F";  // nesting works but hurts readability

switch statement and switch expression:

csharp
switch (day)
{
    case DayOfWeek.Saturday:
    case DayOfWeek.Sunday:            // stacked cases share one body
        Console.WriteLine("Weekend");
        break;                        // C# does not allow fall-through from a non-empty case
    case DayOfWeek.Friday when isHoliday:   // case guard
        Console.WriteLine("Long weekend");
        break;
    default:
        Console.WriteLine("Weekday");
        break;
}

string grade = score switch          // switch expression (C# 8+) returns a value
{
    >= 90 => "A",
    >= 75 and < 90 => "B",
    >= 50 => "C",
    _ => "F"                         // discard = default
};

Loops:

LoopChecks conditionUse when
forBefore each iterationYou know the count / need the index
foreach— iterates a collectionRead every item (can't add/remove items of the collection while looping)
whileBefore (may run 0 times)Repeat until something changes
do-whileAfter (runs at least once)Menus, retry prompts
csharp
for (int i = 0; i < 5; i++) Console.Write(i);           // 01234
for (int i = 10; i > 0; i -= 2) Console.Write(i);       // 108642

foreach (var name in new[] { "Asha", "Ravi" }) Console.WriteLine(name);

int attempts = 0;
while (!Connect() && attempts < 3) attempts++;

string? input;
do
{
    Console.Write("Enter yes or no: ");
    input = Console.ReadLine();
} while (input is not ("yes" or "no"));

for (int i = 1; i <= 10; i++)
{
    if (i % 2 == 0) continue;   // skip the rest of this iteration
    if (i > 7) break;           // leave the loop
    Console.Write(i);           // 1357
}

Nested loops: break only leaves the innermost loop — extract the loops into a method and return, or use a flag. goto exists but is almost never used.

Interview tip: "for vs foreach" — foreach works on any IEnumerable, is cleaner and avoids index bugs; for gives the index and lets you modify elements of an array/list by position. Modifying a List<T> (Add/Remove) inside foreach throws InvalidOperationException.