iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

if / else

C# ships modern conditional flow: if / else if / else, ternary, switch expressions with pattern matching, range / index slicing. Pattern matching replaces big chains of is / as / switch.

if / else, ternary, switch expressions, patterns

EXAMPLE
int age = 36;

// 1) if / else
if (age >= 18)        Console.WriteLine("adult");
else if (age >= 13)   Console.WriteLine("teen");
else                  Console.WriteLine("kid");

// 2) Ternary
string tier = age >= 65 ? "senior" : age >= 18 ? "adult" : "minor";

// 3) Switch EXPRESSION — modern default
string label = tier switch {
    "senior" => "Senior pricing",
    "adult"  => "Standard pricing",
    "minor"  => "Free entry",
    _        => "Unknown",
};

// 4) Patterns
object o = 42;
string describe = o switch {
    int n when n > 0   => $"positive int {n}",
    int                 => "non-positive int",
    string { Length: 0 } => "empty string",
    string s            => $"string of length {s.Length}",
    null                => "null",
    _                   => "something else",
};

// 5) Property patterns + var patterns
public record Order(decimal Total, string Status);

string fee = order switch {
    { Status: "paid", Total:  > 100 } => "5% high-value",
    { Status: "paid" }                  => "3% standard",
    { Status: "refunded" }              => "-100%",
    _                                     => "0%",
};

// 6) Range / Index — slicing
int[] xs = { 10, 20, 30, 40, 50 };
var middle = xs[1..4];   // [20, 30, 40]
var last   = xs[^1];     // 50
var tail   = xs[^2..];   // [40, 50]

Why it matters

Switch expressions + property patterns replace 80% of imperative branching. Lean on them and your business logic reads almost like English.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
int n = 7;
if (n > 10)        Console.WriteLine("big");
else if (n > 0)    Console.WriteLine("small");
else               Console.WriteLine("non-positive");
Try it Yourself »

Discussion

Loading…