The using Statement
The using statement makes sure something is cleaned up as soon as you finish with it, like automatically closing the fridge door. It is used for things like files that must be released.
In this page:
Syntax
using (ResourceType resource = new ResourceType())
{
// use resource; Dispose() is called at the end
}
using var resource = new ResourceType(); // C# 8 declaration form
The using Statement
The using statement ensures an IDisposable object's Dispose() method is called automatically once the block ends, even if an exception occurs — commonly used for files, streams, and database connections.
It's syntactic sugar over a try/finally that calls Dispose(). This prevents resource leaks from forgetting manual cleanup.
Note:
Anything implementing
IDisposable, like StreamReader or StreamWriter, should be wrapped in using.Example: The using Statement
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string path = "notes.txt";
using (StreamWriter writer = new StreamWriter(path))
{
writer.WriteLine("Hello from a using block");
}
using (StreamReader reader = new StreamReader(path))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using a type that does not implement
IDisposablein ausingstatement, which is a compile error. - Using the disposed object after the
usingblock ends, which throwsObjectDisposedException. - Forgetting
usingfor streams or connections, so they stay open.
Chapter Summary
try,catch, andfinallyhandle errors and clean up.- Exception types, custom exceptions,
throw, and exception filters (when) control what is thrown and caught. - The
usingstatement releases resources automatically.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: