DEV Community

Cover image for Level Up Your PRs: 20 Reviewer-Friendly C# One-Liners
Sukhpinder Singh for C# Programming

Posted on • Originally published at Medium

Level Up Your PRs: 20 Reviewer-Friendly C# One-Liners

Two months ago, a background job stalled overnight. Logs were quiet; CPU fine. Turned out one HTTP call never returned. A single one-liner would have saved hours:

var res = await http.GetAsync(url).WaitAsync(TimeSpan.FromSeconds(5));
Enter fullscreen mode Exit fullscreen mode

Every snippet below is the kind of fix I now weave into short narratives (what broke, how I noticed, the one-liner that killed the bug). That blend is performing better than sterile tutorials in 2025.


1) Guard required input (save future you)

_ = arg ?? throw new ArgumentNullException(nameof(arg));
Enter fullscreen mode Exit fullscreen mode

Use it when: You’re one stack trace away from chaos.
Story hook: “The bug wasn’t complex—it was missing.”

2) Null-safe with a sensible default

var city = user?.Address?.City ?? "Unknown";
Enter fullscreen mode Exit fullscreen mode

Use it when: Inputs are messy (forms, APIs).
Narrative angle: “We shipped faster after we picked one default and documented it.”

3) Dispose without ceremony

using var stream = File.OpenRead(path);
Enter fullscreen mode Exit fullscreen mode

Use it when: You can’t afford orphaned handles in long-running services.
Angle: “An elusive file-lock vanished when we stopped being polite and started disposing.”

4) Switch expression for intent

var grade = score switch { >= 90 => "A", >= 80 => "B", _ => "C" };
Enter fullscreen mode Exit fullscreen mode

Use it when: Reviewers keep asking “what does this branch do?”
Angle: “Future teammates read this in one sip.”

5) Dictionary get-or-add (cache happy)

var value = cache.TryGetValue(key, out var v) ? v : cache[key] = Compute(key);
Enter fullscreen mode Exit fullscreen mode

Use it when: You’re de-duping work in hot paths.
Angle: “This line erased a thundering herd.”

6) Count occurrences (no ifs)

counts[key] = counts.GetValueOrDefault(key) + 1;
Enter fullscreen mode Exit fullscreen mode

Use it when: You need a quick histogram from logs.
Angle: “We caught a noisy endpoint by watching counts jump.”

7) Distinct by key (built-in)

var unique = users.DistinctBy(u => u.Email).ToList();
Enter fullscreen mode Exit fullscreen mode

Use it when: Shadow data sources double-insert.
Angle: “Bug reports dropped when we kept just the first truth.”

8) Group + count to dictionary

var byExt = files.GroupBy(f => Path.GetExtension(f))
                 .ToDictionary(g => g.Key, g => g.Count());
Enter fullscreen mode Exit fullscreen mode

Use it when: You need a dashboard metric now.
Angle: “One liner, instant insight, zero BI tickets.”

9) Top-N fast

var top3 = items.OrderByDescending(x => x.Score).Take(3).ToList();
Enter fullscreen mode Exit fullscreen mode

Use it when: Stakeholders want “the top offenders.”
Angle: “Screenshots sell decisions.”

10) Stream huge logs safely

var errors = File.ReadLines(path).Where(l => l.Contains("ERROR"));
Enter fullscreen mode Exit fullscreen mode

Use it when: Memory blows up tailing 40GB logs.
Angle: “We debugged without waking the ops pager.”

11) Serialize quickly (built-in)

var json = JsonSerializer.Serialize(model);
Enter fullscreen mode Exit fullscreen mode

Use it when: You need diagnostics or cache blobs.
Angle: “Cut dependency bloat; used the box.”

12) Deserialize (defensive)

var dto = JsonSerializer.Deserialize<MyDto>(json)!;
Enter fullscreen mode Exit fullscreen mode

Use it when: Inputs are trusted or pre-validated.
Angle: “‘!’ means we checked—write it down.”

13) Parse with fallback

var retries = int.TryParse(s, out var n) ? n : 3;
Enter fullscreen mode Exit fullscreen mode

Use it when: Config may be absent in one region.
Angle: “Defaults are decisions. Make them visible.”

14) Tail of a string (ranges)

var last10 = text[^10..];
Enter fullscreen mode Exit fullscreen mode

Use it when: Displaying compact IDs or hashes.
Angle: “Readable slices = fewer off-by-ones.”

15) Create parent folder idempotently

Directory.CreateDirectory(Path.GetDirectoryName(path)!);
Enter fullscreen mode Exit fullscreen mode

Use it when: Writing exports from serverless or jobs.
Angle: “Race conditions? Not today.”

16) Modern param guard

ArgumentException.ThrowIfNullOrEmpty(name);
Enter fullscreen mode Exit fullscreen mode

Use it when: You want consistent guardrails.
Angle: “Standard helpers beat bespoke cleverness.”

17) Trim without NRE

var clean = input?.Trim() ?? string.Empty;
Enter fullscreen mode Exit fullscreen mode

Use it when: Sanitizing form/query values.
Angle: “We stopped chasing invisible spaces.”

18) Flatten batches

var all = batches.SelectMany(b => b).ToList();
Enter fullscreen mode Exit fullscreen mode

Use it when: An API paginates but you need a unified view.
Angle: “Analytics pipelines got one step simpler.”

19) Fire many tasks together

await Task.WhenAll(work.Select(DoAsync));
Enter fullscreen mode Exit fullscreen mode

Use it when: Fan-out jobs or microservice calls.
Angle: “Throughput tripled; complexity didn’t.”

20) Add timeouts (no custom CTS)

var res = await client.GetAsync(url).WaitAsync(TimeSpan.FromSeconds(5));
Enter fullscreen mode Exit fullscreen mode

Use it when: A slow downstream can freeze your world.
Angle: “This single line ended a 3 a.m. incident.”


Closing thought

These aren’t party tricks—they’re habits. Each one removed a failure mode in real code I ship.

If you’ve got a sharper one-liner (or a story where one saved a release), drop it in the comments.

Top comments (0)