DEV Community

Cover image for Level Up Your PRs: 20 Reviewer-Friendly C# One-Liners
C# Programming profile imageSukhpinder Singh
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:

varres=awaithttp.GetAsync(url).WaitAsync(TimeSpan.FromSeconds(5));
Enter fullscreen modeExit 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??thrownewArgumentNullException(nameof(arg));
Enter fullscreen modeExit 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

varcity=user?.Address?.City??"Unknown";
Enter fullscreen modeExit 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

usingvarstream=File.OpenRead(path);
Enter fullscreen modeExit 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

vargrade=scoreswitch{>=90=>"A",>=80=>"B",_=>"C"};
Enter fullscreen modeExit 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)

varvalue=cache.TryGetValue(key,outvarv)?v:cache[key]=Compute(key);
Enter fullscreen modeExit 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 modeExit 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)

varunique=users.DistinctBy(u=>u.Email).ToList();
Enter fullscreen modeExit 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

varbyExt=files.GroupBy(f=>Path.GetExtension(f)).ToDictionary(g=>g.Key,g=>g.Count());
Enter fullscreen modeExit fullscreen mode

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

9) Top-N fast

vartop3=items.OrderByDescending(x=>x.Score).Take(3).ToList();
Enter fullscreen modeExit fullscreen mode

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

10) Stream huge logs safely

varerrors=File.ReadLines(path).Where(l=>l.Contains("ERROR"));
Enter fullscreen modeExit fullscreen mode

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

11) Serialize quickly (built-in)

varjson=JsonSerializer.Serialize(model);
Enter fullscreen modeExit fullscreen mode

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

12) Deserialize (defensive)

vardto=JsonSerializer.Deserialize<MyDto>(json)!;
Enter fullscreen modeExit fullscreen mode

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

13) Parse with fallback

varretries=int.TryParse(s,outvarn)?n:3;
Enter fullscreen modeExit 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)

varlast10=text[^10..];
Enter fullscreen modeExit 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 modeExit 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 modeExit fullscreen mode

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

17) Trim without NRE

varclean=input?.Trim()??string.Empty;
Enter fullscreen modeExit fullscreen mode

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

18) Flatten batches

varall=batches.SelectMany(b=>b).ToList();
Enter fullscreen modeExit 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

awaitTask.WhenAll(work.Select(DoAsync));
Enter fullscreen modeExit fullscreen mode

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

20) Add timeouts (no custom CTS)

varres=awaitclient.GetAsync(url).WaitAsync(TimeSpan.FromSeconds(5));
Enter fullscreen modeExit 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)