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

Operators

C# operators follow the C-family conventions plus modern additions: null-coalescing (??), null-conditional (?., ?[]), pattern matching with is and switch.

Modern operators worth knowing

EXAMPLE
int    a = 17, b = 5;
double x = (double)a / b;       // 3.4 — explicit cast first
int    n = checked(int.MaxValue + 1);   // throws OverflowException

// Null-coalescing
string? name = MaybeName();
string  pretty = name ?? "Anonymous";
name ??= "default";              // assign only if currently null

// Null-conditional
int? len = name?.Length;          // null when name is null, else int
User? u  = users?.FirstOrDefault();
string? city = u?.Address?.City;

// Pattern matching
object o = 42;
if (o is int n2 and > 0) Console.WriteLine($"positive int {n2}");

string describe = o switch {
    int n   when n > 0 => $"positive int {n}",
    int     => "non-positive int",
    string s            => $"string of length {s.Length}",
    null               => "null",
    _                   => "something else",
};

// Range / index — slices on strings & arrays
int[] xs = { 10, 20, 30, 40, 50 };
var middle = xs[1..4];           // [20, 30, 40]
var last   = xs[^1];             // 50  — ^N counts from end

Why it matters

??= on lazy-init fields, ?. through deep object graphs, and pattern matching in switch replace pages of imperative null-checking. Default-on for modern projects.

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

Example

Example
int x = 7, y = 3;
Console.WriteLine(x + y);
Console.WriteLine(x / y);   // 2 (integer)
Console.WriteLine(x % y);   // 1
Try it Yourself »

Discussion

Loading…