The using statement helps automatically clean up resources like files or connections when you are done with them. This keeps your program neat and avoids problems like memory leaks.
0
0
Using statement for resource cleanup in C Sharp (C#)
Introduction
When opening a file to read or write and you want to close it automatically.
When working with database connections that need to be closed after use.
When using objects that hold system resources like streams or graphics handles.
When you want to ensure resources are released even if an error happens.
Syntax
C Sharp (C#)
using (ResourceType resource = new ResourceType()) { // Use the resource here } // Resource is automatically cleaned up here
The resource must implement IDisposable interface.
The resource is disposed automatically at the end of the using block.
Examples
This opens a file and reads all its content. The file is closed automatically after the block.
C Sharp (C#)
using (var file = new StreamReader("file.txt")) { string content = file.ReadToEnd(); Console.WriteLine(content); }
This example uses the newer C# syntax where the using statement declares a variable without braces.
C Sharp (C#)
using var connection = new SqlConnection(connectionString); connection.Open(); // Use connection here // Connection is closed automatically when out of scope
Sample Program
This program writes a line to a file and then reads it back. Both file operations use the using statement to ensure the file is closed automatically.
C Sharp (C#)
using System; using System.IO; class Program { static void Main() { string path = "example.txt"; // Write text to file using 'using' to auto-close using (StreamWriter writer = new StreamWriter(path)) { writer.WriteLine("Hello, using statement!"); } // Read text from file using 'using' to auto-close using (StreamReader reader = new StreamReader(path)) { string text = reader.ReadToEnd(); Console.WriteLine(text); } } }
OutputSuccess
Important Notes
Always use using with resources that implement IDisposable to avoid forgetting to release them.
The using statement helps prevent resource leaks and makes code cleaner.
Summary
The using statement automatically cleans up resources when done.
It works with objects that implement IDisposable.
Using it prevents resource leaks and makes code safer.