Ensuring Object Disposal in C# with using statement

You can use the using statement in C# for ensuring that the object is disposed when it goes out of scope. The using statement provides an easy way for the user to save them from writing extra code for this scenario.

Take the below code snippet as an example where we use FileStream and StreamWriter objects. We might have to call the dispose method in the finally block as shown below.

FileStream fileStream = new FileStream("senthilkumar.txt", FileMode.Create);
try
{
    StreamWriter streamWriter = new StreamWriter(fileStream);
    try
    {
        streamWriter.WriteLine("This is a sample text");
    }
    finally
    {
        ((IDisposable) streamWriter).Dispose();
    }
}
finally
{

    ((IDisposable) fileStream).Dispose();

}

The same can be written better with the using statement and yet ensuring that the object is disposed when it is out of scope.

using (FileStream fileStream = new FileStream("senthilkumar.txt", FileMode.Create))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        streamWriter.WriteLine("This is a sample text");
    }
}

Note that the type must implement Idisposable interface when you want to use it within the using statement.If the type doesnot implement the interface , you will get an compiler error similar to this

type used in a using statement must be implicitly convertible to ‘System.IDisposable’

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...