Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Using Statement vs Using Declaration

Understand the practical difference between C# using statements and using declarations: how scope affects when Dispose is called, when to choose each form, and common pitfalls.

~5 min readC#
#IDisposable#Resource Management#C# Syntax#Code Scope
A visual comparison of C# using statement and using declaration showing scope and disposal timing.

When you work with a type that implements IDisposable, the using keyword is the standard way to ensure the resource is released. The classic using statement disposes at the closing brace of its block. The C# 8 using declaration disposes at the end of the enclosing scope. The practical choice between the two comes down to the exact point where Dispose() is called, which can matter in long-running methods or loops.

The Classic Using Statement

The using statement has been part of C# since version 1.0. It ensures that Dispose() is called when execution leaves the block, even if an exception is thrown. The syntax explicitly defines the lifetime of the resource with braces.

csharp
using (var reader = new StreamReader("file.txt")) { string line = reader.ReadLine(); // resource is alive here } // reader is disposed here

Inside the block, reader is fully usable. After the closing brace, the compiler inserts a call to Dispose() in a finally block, so cleanup happens even on early returns or exceptions. The variable is not accessible after the block, which prevents accidental use of a disposed object.

The Using Declaration

C# 8 introduced the using declaration, which removes the explicit block. You declare the variable with using, and the compiler disposes it at the end of the enclosing scope.

csharp
using var writer = new StreamWriter("output.txt"); writer.WriteLine("Hello"); // writer is disposed when the enclosing scope ends

The enclosing scope is the current block, method, or other containing block. Disposal happens at the end of that scope, not at a dedicated using block. That is the main distinction to remember.

Scope Differences and Disposal Timing

The most significant difference is when Dispose() is called. With a using statement, disposal occurs at the closing brace. With a using declaration, disposal occurs at the end of the containing scope.

csharp
void Process() { using var conn = new SqlConnection(connectionString); conn.Open(); // ... some work ... using var cmd = conn.CreateCommand(); cmd.CommandText = "SELECT ..."; // ... more work ... // conn and cmd are disposed here, at the end of Process }

Both conn and cmd stay alive until the method returns. If the connection should be released earlier, use a using statement to control the exact disposal point. In a long method, keeping resources alive longer than necessary can hold locks or keep handles open.

Practical Impact on Resource Lifetime

For short methods, the difference is often negligible. But if a method opens a file, reads a header, then performs a CPU-heavy calculation, a using declaration keeps the file handle open during the calculation. A using statement can close the file immediately after the read. The following example compares the two:

csharp
byte[] header = new byte[16]; // Using declaration using var file = File.OpenRead("data.bin"); file.Read(header, 0, 16); // file stays open during the expensive calculation ComputeChecksum(header); // Using statement byte[] header2 = new byte[16]; using (var file = File.OpenRead("data.bin")) { file.Read(header2, 0, 16); } // file is closed before the expensive calculation ComputeChecksum(header2);

In the first version, the file handle remains open until the method ends. In the second, it is released before the computation. This matters when resources are scarce or when you want to avoid holding locks longer than necessary.

Nested Using and Scope Confusion

Using declarations can be nested naturally, but their scope can lead to unexpected behavior when combined with loops or conditional blocks. A common case is a loop:

csharp
for (int i = 0; i < 10; i++) { using var stream = new MemoryStream(); // ... use stream ... } // Each stream is disposed at the end of each iteration

The declaration is inside the loop body, so the resource is disposed at the end of each iteration. If the declaration is outside the loop, the resource is disposed only when the enclosing scope ends, which might be after all iterations:

csharp
using var stream = new MemoryStream(); for (int i = 0; i < 10; i++) { // same stream reused, not disposed until after the loop }

That behavior is intentional, but the using statement makes the lifetime explicit and can be easier to read.

Handling Multiple Resources

A using statement can be stacked when you need to dispose multiple resources in a well-defined order:

csharp
using (var a = new ResourceA()) using (var b = new ResourceB()) { // both are disposed in reverse order }

Using declarations cannot be stacked in that exact form. If you write two separate declarations at the same scope, both are disposed at the end of that scope. To dispose them at the same point as the block above, wrap them in an explicit block or use stacked using statements.

Language Version and Compatibility

The using declaration is available in C# 8 and later. If a project targets an older language version, you must use the using statement. Current .NET SDKs support C# 8 and later, so this is rarely a problem unless you are maintaining legacy code or have explicitly set LangVersion to an older value.

Choosing Between the Two Forms

Use the using declaration when the resource should live for the entire enclosing scope and you want to reduce nesting. That is common for resources used throughout a method, such as a database connection opened at the start and used by multiple queries.

Use the using statement when you need to control the exact disposal point, especially when the resource is only needed for a small portion of the method or when you want the lifetime visually explicit to readers.

A practical rule: If a resource is used throughout a method and avoiding extra indentation matters, prefer the using declaration. If the resource is needed only in a small block, or if early release matters, prefer the using statement.

Common Pitfalls with Using Declarations

One common mistake is assuming a using declaration inside a switch section is disposed at the end of that section. Unless the declaration is inside its own block, the disposal point is tied to the containing block, not to the break. If you need a resource to be released at the end of a case, use a using statement or add explicit braces.

csharp
switch (mode) { case "read": using (var reader = new StreamReader("file.txt")) { // reader is disposed at the end of this block } break; case "write": break; }

Another pitfall is relying on a using declaration to release a resource before a later operation that does not need it. As shown earlier, the resource remains alive until the end of the method. Always consider whether any work after the declaration still needs the resource.

Maintainability and Code Review

Using declarations make code more concise, but they can hide the exact disposal point. A reviewer must inspect the enclosing scope to know when the resource is released. Using statements make the disposal point local and explicit, which is easier to reason about in longer methods.

On the other hand, using declarations reduce indentation and can make the primary logic more visible. For a short method where the resource is used throughout, that is often a good trade-off. For a longer method with multiple resources, using statements provide clearer boundaries and reduce the risk of accidental resource retention.

Final Code Example: Combining Both

The two forms can be mixed in one method. A method that opens a file and writes a log entry might use a using declaration for the file and a using statement for the logger:

csharp
void ProcessFile(string path) { using var file = File.OpenRead(path); // process file... using (var logger = new StreamWriter("log.txt", append: true)) { logger.WriteLine("Processing complete"); } // logger is disposed here, before method returns // file is still open here, but will be disposed when method ends }

This shows that the two forms are not mutually exclusive. The right choice depends on the resource's intended lifetime, whether early cleanup matters, and how much nesting you want in the code.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.