How to Use of ‘Using’ Statement in .NET?

In .NET, the `using` statement is used to ensure that certain objects are properly disposed of when they are no longer needed. It is primarily used with objects that implement the `IDisposable` interface. The `IDisposable` interface defines a single method, `Dispose()`, which is called to release unmanaged resources used by an object.

Here’s how the `using` statement works:

1. Resource Acquisition: When you use the `using` statement, you create a scope in which an object is instantiated and used. This object typically represents a resource that needs to be properly managed, such as a file stream, database connection, or network socket.

2. Automatic Disposal: After the block of code within the `using` statement completes execution, the `Dispose()` method of the object is automatically called. This ensures that any unmanaged resources held by the object are released in a timely manner.

3. Exception Safety: The `using` statement ensures that the `Dispose()` method is called even if an exception occurs within the block of code. This helps prevent resource leaks and ensures that resources are properly cleaned up, even in the event of an error.

Here’s an example of how you can use the `using` statement with a `FileStream` object to read data from a file:

using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
// Open a file and read its contents
string filePath = "example.txt";
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
StreamReader reader = new StreamReader(fileStream);
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
} // Dispose() method is automatically called here
}
}

In this example:

– We create a `FileStream` object to open a file named “example.txt” for reading.
– We use the `using` statement to ensure that the `FileStream` object is properly disposed of after we finish reading from the file.
– Inside the `using` block, we create a `StreamReader` object to read text from the file.
– After the `using` block completes execution, the `Dispose()` method of the `FileStream` object is automatically called, releasing any resources associated with the file stream.