Common C# Pitfalls
Even experienced developers coming from other languages, or C# developers who haven't kept up with recent language changes, run into a recurring set of mistakes. Some are subtle compiler-visible bugs (closures capturing the wrong variable), some are silent runtime bugs (comparing reference equality when value equality was intended), and some are performance traps that only show up under load (accidental boxing, LINQ re-enumeration). This topic collects the pitfalls that recur most often in real codebases and code review.
Cricket analogy: Even a seasoned batsman like Rahul Dravid could fall into the same lbw trap repeatedly without reviewing technique; C# devs coming from other languages repeatedly trip on closures, equality, and boxing until they study the recurring dismissal patterns.
async void
async void methods cannot be awaited by their caller, and any exception thrown inside one cannot be caught by a surrounding try/catch — it propagates directly to the SynchronizationContext (crashing the process in many hosts) instead of onto a Task the caller could observe. async void should be reserved strictly for event handlers, which require it because delegate-based event signatures predate async/await. Every other async method should return Task or Task<T> (or ValueTask/ValueTask<T> for hot-path allocation avoidance). Exceptions from async void methods cannot be caught by the caller with a normal try/catch, even if the call site wraps the invocation. This is one of the most dangerous silent-failure patterns in C# and is a very common interview and code-review topic.
Cricket analogy: An appeal for a wicket heard only by the umpire (SynchronizationContext) while the fielding captain (caller) never sees it - an exception in async void escapes past the try/catch straight to the runtime and can crash the match.
Closures Over Loop Variables
Prior to C# 5, a for loop's iteration variable was a single variable reused across iterations, so lambdas capturing it inside the loop body would all see the final value after the loop finished. C# 5 fixed this specifically for foreach (each iteration gets a fresh variable), but a classic for (int i = 0; ...) loop still uses one mutable variable across iterations — capturing i directly in a closure still captures the same variable, not a per-iteration snapshot.
Cricket analogy: In a classic for loop, capturing the shared iterator is like ten fielders sharing one radio call sign 'player i' - by the over's end they all answer to the last number set, unlike foreach handing each a fresh mic per over.
var actions = new List<Action>();
for (int i = 0; i < 3; i++)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (var action in actions)
action(); // prints 3, 3, 3 — all captured the same 'i'
// Fix: capture a fresh local per iteration
var fixedActions = new List<Action>();
for (int i = 0; i < 3; i++)
{
int local = i;
fixedActions.Add(() => Console.WriteLine(local));
}
foreach (var action in fixedActions)
action(); // prints 0, 1, 2Reference Equality vs. Value Equality
The == operator on class types defaults to reference equality (are these the same object?) unless the class overloads == or overrides Equals. record types generate value-based equality automatically, comparing all properties, which is why swapping a class for a record can silently change == semantics for existing code — usually for the better, but it's a change worth being deliberate about. string is a special case: it's a reference type, but == is overloaded to perform value comparison.
Cricket analogy: Reference equality judges two players 'equal' only if they're literally the same person, whereas a record's value equality judges two scorecards equal if every stat matches even on different sheets; strings behave like player names, compared by spelling despite being objects.
Boxing is another quiet performance pitfall: passing a value type (like int) to a method expecting object, or storing it in a non-generic collection like ArrayList, allocates a heap box to wrap the value. Generic collections (List<int>) avoid this entirely because they're specialized per value type at JIT time — one more reason to prefer List<T> over legacy non-generic collections. Because most LINQ operators are lazily evaluated, calling .Count() and then .ToList() on the same IEnumerable<T> query re-runs the entire query pipeline twice — expensive if the source involves a database call or heavy computation, and dangerous if the source is not idempotent (e.g. it consumes an IEnumerator that can only be iterated once, like reading a stream). Materializing the result once with .ToList() and reusing that list avoids the duplicate work and any non-idempotence hazards.
- async void swallows exceptions from the caller's perspective and should be reserved for event handlers only.
- Capturing a classic for-loop's iteration variable in a closure captures the shared mutable variable, not a per-iteration snapshot; foreach fixed this in C# 5 but for-loops did not change.
- == on class types defaults to reference equality unless overridden; record types get value equality automatically.
- Boxing value types into object or non-generic collections silently allocates on the heap.
- Re-enumerating a lazily evaluated LINQ query re-executes its entire pipeline every time.
- Materializing a query once with ToList()/ToArray() avoids duplicate work and non-idempotence bugs.
Practice what you learned
1. Why is `async void` considered dangerous outside of event handlers?
2. What value does a lambda print when capturing a classic `for (int i...)` loop variable without a local copy?
3. What is the default behavior of `==` for a plain `class` type that does not override it?
4. What causes boxing in C#?
5. Why can calling both .Count() and .ToList() on the same lazily-evaluated LINQ query be wasteful or dangerous?
Was this page helpful?
You May Also Like
async/await Explained
Understand how async and await let you write non-blocking, readable asynchronous code in C#, and how the compiler transforms it into a state machine.
Lambda Expressions
Lambda expressions provide concise, inline syntax for anonymous functions, forming the backbone of LINQ, delegates, and functional-style C# code.
LINQ Basics
Language Integrated Query lets you write expressive, type-safe queries directly in C# over collections, databases, and XML using a unified syntax.
C# Interview Questions
A curated set of common C# interview questions and precise answers covering value vs reference types, async/await, LINQ, and object-oriented design.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics