🔧 Fix a Using Declaration Disposing in the Wrong Order
A C# 8 using declaration (using var x = ...;, with no braces) disposes its resource at the end of the enclosing scope rather than at an explicit point you control, and when two such declarations appear back to back, they’re disposed in reverse declaration order automatically — which is usually what you want, except when one resource actually depends on the other staying alive slightly longer than its own declared scope suggests.
🔎 The Problem
using var connection = new SqlConnection(connStr); connection.Open(); using var transaction = connection.BeginTransaction(); // ... work ... // Method ends: transaction disposed first, then connection - correct here. // But if a THIRD resource is added that the transaction's rollback // logic depends on, and it's declared BEFORE the transaction, // it gets disposed AFTER the transaction needs it - reverse order // isn't automatically the right order for every dependency graph.
✅ Fix: Make Dependent Disposal Explicit Instead of Relying on Order
- When one resource’s disposal logic depends on another still being valid, fall back to an explicit
using (...) { }block (or atry/finally) where you control the exact nesting, rather than trusting declaration order to match the dependency order. - Add a code comment right at the declaration noting the dependency, since ‘declared after, disposed before’ reverse ordering is easy for a future editor to get wrong when adding a new resource in between.
- Where the dependency is strict, wrap the dependent resources in their own small helper type that implements
IDisposableand encodes the correct teardown order internally, so the call site can’t get the order wrong by adding an unrelated declaration.
Reverse declaration order is the default for using declarations, not a guarantee about which resource genuinely needs to outlive which.




