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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...