C# using
last modified November 15, 2026
This article shows how to use the using keyword in C#.
The using keyword has two unrelated roles:
- the using statement and using declaration release
resources: they guarantee that an object's
Disposemethod is called when the object goes out of scope, - the using directive imports namespaces, creates aliases, and,
in the
using staticform, imports the static members of a type.
C# using declaration
Objects that hold unmanaged resources, such as files, network connections,
or database connections, implement the IDisposable interface.
Its Dispose method releases the resources and should be called
as soon as the object is no longer needed; the garbage collector runs at
unpredictable times. The using keyword calls
Dispose automatically, even when an exception is thrown.
The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.
Some examples read this text file.
using var fs = new FileStream("thermopylae.txt", FileMode.Open, FileAccess.Read);
using var sr = new StreamReader(fs);
string content = sr.ReadToEnd();
Console.Write(content);
The program reads the whole file with a StreamReader.
using var fs = new FileStream("thermopylae.txt", FileMode.Open, FileAccess.Read);
using var sr = new StreamReader(fs);
This is the using declaration, available since C# 8. The variables
are disposed at the end of the enclosing scope, here at the end of the
program. Both FileStream and StreamReader
implement IDisposable.
$ dotnet run The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece.
C# using statement
The older form, the using statement, has its own block; the object
is disposed when the block ends. To show when disposal happens, the next
examples use a Resource class that prints a message in its
Dispose method.
using (var r1 = new Resource("first"))
{
Console.WriteLine($"Working with {r1.Name}");
}
Console.WriteLine("---");
using (var r2 = new Resource("outer"))
using (var r3 = new Resource("inner"))
{
Console.WriteLine("Working with two resources");
}
Console.WriteLine("---");
using (Resource r4 = new("A"), r5 = new("B"))
{
Console.WriteLine("Two resources in one statement");
}
class Resource(string name) : IDisposable
{
public string Name => name;
public void Dispose() => Console.WriteLine($"Disposing {name}");
}
We create resources in three using statements.
using (var r1 = new Resource("first"))
{
Console.WriteLine($"Working with {r1.Name}");
}
The resource is disposed right after the block.
using (var r2 = new Resource("outer"))
using (var r3 = new Resource("inner"))
{
Console.WriteLine("Working with two resources");
}
Stacked using statements share one block. They are nested, so
the resources are disposed in reverse order of creation.
using (Resource r4 = new("A"), r5 = new("B"))
Several variables of the same type can be declared in one statement. They are disposed in reverse order too.
$ dotnet run Working with first Disposing first --- Working with two resources Disposing inner Disposing outer --- Two resources in one statement Disposing B Disposing A
C# using declaration scope
A using declaration disposes its object at the end of the block in which it is declared, in reverse order of the declarations.
Process();
Console.WriteLine("Back in the main program");
void Process()
{
Console.WriteLine("Process started");
using var log = new Resource("log");
using var db = new Resource("database");
Console.WriteLine("Working");
if (true)
{
using var tmp = new Resource("temp");
Console.WriteLine("Inner block");
}
Console.WriteLine("Process ending");
}
class Resource(string name) : IDisposable
{
public void Dispose() => Console.WriteLine($"Disposing {name}");
}
We declare resources at two levels of nesting.
using var log = new Resource("log");
using var db = new Resource("database");
The two resources live until the end of the Process method.
if (true)
{
using var tmp = new Resource("temp");
Console.WriteLine("Inner block");
}
The temporary resource is disposed at the end of the inner block. A using declaration is shorter than a statement, but it can keep a resource open longer than needed; a using statement with an explicit block is the better choice when a resource should be released early.
$ dotnet run Process started Working Inner block Disposing temp Process ending Disposing database Disposing log Back in the main program
C# using and exceptions
The object is disposed even if an exception leaves the scope.
try
{
using var res = new Resource("connection");
Console.WriteLine("Doing work");
throw new InvalidOperationException("something went wrong");
}
catch (InvalidOperationException e)
{
Console.WriteLine($"Caught: {e.Message}");
}
class Resource(string name) : IDisposable
{
public void Dispose() => Console.WriteLine($"Disposing {name}");
}
We throw an exception while a resource is in use.
using var res = new Resource("connection");
Console.WriteLine("Doing work");
throw new InvalidOperationException("something went wrong");
The resource is disposed before the exception reaches the
catch block, as the order of the messages shows.
$ dotnet run Doing work Disposing connection Caught: something went wrong
C# try/finally equivalent
The compiler translates using into a try/finally
statement that calls Dispose in the finally block.
Before C# had the using statement, the code was written by
hand.
FileStream? fs = null;
StreamReader? sr = null;
try
{
fs = new FileStream("thermopylae.txt", FileMode.Open, FileAccess.Read);
sr = new StreamReader(fs);
Console.WriteLine(sr.ReadLine());
}
finally
{
sr?.Dispose();
fs?.Dispose();
}
Console.WriteLine($"Stream closed: {!fs.CanRead}");
We read the first line of the file and release the resources in a
finally block.
finally
{
sr?.Dispose();
fs?.Dispose();
}
The variables must be declared before the try block and checked
for null, because the constructors may throw before the
objects are created. The Close method of streams calls
Dispose as well.
For simple file reading, File.ReadAllText or
File.ReadLines open and close the file themselves.
$ dotnet run The Battle of Thermopylae was fought between an alliance of Greek city-states, Stream closed: True
C# await using
Resources whose release involves I/O, such as flushing buffers over the
network, implement IAsyncDisposable. The await using
statement and declaration call and await its DisposeAsync
method.
await using (var conn = new Connection("db1"))
{
await conn.QueryAsync();
}
await using var conn2 = new Connection("db2");
await conn2.QueryAsync();
Console.WriteLine("End of program");
class Connection(string name) : IAsyncDisposable
{
public async Task QueryAsync()
{
await Task.Delay(10);
Console.WriteLine($"Query on {name} done");
}
public async ValueTask DisposeAsync()
{
await Task.Delay(10);
Console.WriteLine($"{name} closed asynchronously");
}
}
We use an asynchronous connection with both forms.
await using (var conn = new Connection("db1"))
{
await conn.QueryAsync();
}
The statement form disposes the connection at the end of the block.
await using var conn2 = new Connection("db2");
The declaration form disposes it at the end of the program, after the last message.
public async ValueTask DisposeAsync()
{
await Task.Delay(10);
Console.WriteLine($"{name} closed asynchronously");
}
DisposeAsync returns a ValueTask. The delay stands
for asynchronous cleanup work.
$ dotnet run Query on db1 done db1 closed asynchronously Query on db2 done End of program db2 closed asynchronously
C# using with ref struct
A ref struct could not implement interfaces before C# 13.
For such types, using works with any accessible
Dispose method; this is the pattern-based using.
using (var buf = new Buffer(64))
{
Console.WriteLine($"Using a buffer of {buf.Size} bytes");
}
Console.WriteLine("Done");
ref struct Buffer(int size)
{
public int Size => size;
public void Dispose() => Console.WriteLine("Buffer released");
}
The Buffer type has a Dispose method but does not
implement IDisposable.
ref struct Buffer(int size)
{
public int Size => size;
public void Dispose() => Console.WriteLine("Buffer released");
}
The using statement finds the method by its name. The pattern
applies to ref struct types only; classes and ordinary structs
must implement IDisposable.
$ dotnet run Using a buffer of 64 bytes Buffer released Done
C# using directive
The using directive imports the types of a namespace, so that they can be
used without the namespace prefix. Projects for .NET 6 and later have
implicit global usings enabled; a console project imports
System, System.Collections.Generic,
System.IO, System.Linq,
System.Net.Http, System.Threading, and
System.Threading.Tasks automatically.
using System.Text;
var sb = new StringBuilder();
sb.Append("an old falcon");
sb.Append(' ');
sb.Append("in the sky");
int[] vals = [1, 4, -5, 3, -3, -1, 0, 2, 6, 7];
var positive = vals.Where(e => e > 0);
Console.WriteLine(sb);
Console.WriteLine(string.Join(" ", positive));
The program uses types from System.Text and
System.Linq.
using System.Text;
StringBuilder lives in System.Text, which is not
among the implicit usings, so we import it. Without the directive, we would
have to write System.Text.StringBuilder.
var positive = vals.Where(e => e > 0);
The Where extension method comes from
System.Linq, which is imported implicitly.
$ dotnet run an old falcon in the sky 1 4 3 2 6 7
C# global using
The global using directive, available since C# 10, applies to
all files of the project. It is common to collect such directives in one
file.
global using System.Text; global using System.Text.RegularExpressions;
This file imports two namespaces for the whole project.
var sb = new StringBuilder("Visit us at ");
sb.Append("zetcode.com");
string text = sb.ToString();
Console.WriteLine(text);
Console.WriteLine(Regex.IsMatch(text, @"\w+\.com"));
The program uses StringBuilder and Regex without
any using directive of its own.
Console.WriteLine(Regex.IsMatch(text, @"\w+\.com"));
The types are found through the global usings. Global usings can also be
declared in the project file with <Using Include="System.Text" />
items.
$ dotnet run Visit us at zetcode.com True
C# using alias
The using directive can create an alias for a namespace or a type. Since C# 12, an alias can name any type, including tuples, arrays, and generic types.
using Terminal = System.Console;
using Json = System.Text.Json.JsonSerializer;
using Point = (int X, int Y);
using Names = System.Collections.Generic.List<string>;
using System.Timers;
using Timer = System.Threading.Timer;
Terminal.WriteLine("Hello there!");
Point p = (3, 4);
Terminal.WriteLine($"Point: {p.X}, {p.Y}");
Names names = ["Jane", "Peter", "Lucy"];
Terminal.WriteLine(Json.Serialize(names));
using var timer = new Timer(_ => { }, null, Timeout.Infinite, Timeout.Infinite);
Terminal.WriteLine(timer.GetType().FullName);
We create several kinds of aliases.
using Terminal = System.Console; using Json = System.Text.Json.JsonSerializer;
These aliases give classes shorter or different names.
using Point = (int X, int Y); using Names = System.Collections.Generic.List<string>;
The C# 12 alias of a named tuple and of a closed generic type. Note that the
alias does not create a new type: Point is just another name
for (int X, int Y).
using System.Timers; using Timer = System.Threading.Timer;
Aliases resolve name conflicts. Both System.Timers and the
implicitly imported System.Threading contain a
Timer class; without the alias, the compiler reports error
CS0104, an ambiguous reference. The alias takes precedence over the types
imported by the namespace directives.
$ dotnet run Hello there! Point: 3, 4 ["Jane","Peter","Lucy"] System.Threading.Timer
C# using static directive
The using static directive imports the static members and
nested types of a type, so they can be used without the type name. It also
works with enumerations.
using static System.Math;
using static System.ConsoleColor;
double c = Sqrt(Pow(3, 2) + Pow(4, 2));
Console.WriteLine($"Hypotenuse: {c}");
Console.WriteLine($"PI rounded: {Round(PI, 4)}");
ConsoleColor[] colors = [Red, Green, Blue];
Console.WriteLine(string.Join(", ", colors));
We import the members of Math and of the
ConsoleColor enumeration.
double c = Sqrt(Pow(3, 2) + Pow(4, 2));
The Sqrt and Pow methods are called without the
Math. prefix. This suits code with many calls, such as numeric
formulas.
ConsoleColor[] colors = [Red, Green, Blue];
The enumeration members are used without the type name.
$ dotnet run Hypotenuse: 5 PI rounded: 3.1416 Red, Green, Blue
Source
using statement - C# reference
using directive - C# reference
In this article we have worked with the using statement and
the using directive in C#. See also the
StreamReader,
FileStream, and
namespace tutorials.
Author
List all C# tutorials.