The using statement in C# is used for automatically managing the lifetime of disposable resources—typically unmanaged resources like files, database connections, streams, etc.
Purpose:
The using statement ensures that the object’s Dispose() method is called
automatically, even if an exception occurs. This helps:
Prevent memory leaks.
Release file handles or DB connections properly.
Keep resource management safe and concise.
Syntax:
using (var resource = new SomeDisposableResource())
{
// Use the resource
}
// resource.Dispose() is called automatically here
Applies to:
Any class that implements the IDisposable interface, such as:
StreamReader, FileStream, SqlConnection
XmlWriter, MemoryStream, HttpClient
Example:
using (var file = new StreamReader("file.txt"))
{
string content = file.ReadToEnd();
}
// StreamReader.Dispose() is automatically called here
C# 8.0+:
In newer versions of C#, you can use a using declaration:
using var file = new StreamReader("file.txt");
// No need for braces; file is disposed at the end of the scope
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
The
usingstatement in C# is used for automatically managing the lifetime of disposable resources—typically unmanaged resources like files, database connections, streams, etc.Purpose:
The
usingstatement ensures that the object’sDispose()method is called automatically, even if an exception occurs. This helps:Syntax:
Applies to:
Any class that implements the
IDisposableinterface, such as:StreamReader,FileStream,SqlConnectionXmlWriter,MemoryStream,HttpClientExample:
C# 8.0+:
In newer versions of C#, you can use a using declaration: