Object disposal in C#

Created by
Sunday, June 26, 2016

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();

}

Tags:
c#
filestream
0
Rating
1 2 3 4 5

Save

Saved

Report

Reported
Reasons
Cancel
0 comments