Wednesday, March 5, 2008

Correct usage of IDisposable.

Original source code (write a text to text file):
--------------------------------------------------------------------
StreamWriter writer = new StreamWriter(filePath);
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
writer.Flush();
--------------------------------------------------------------------

Class StreamWriter implements interface IDisposable, then we should call method Dispose(), which closes all unmanaged resources (and executes another 'destructor' actions).

Picture (Device Independent Bitmap)

Original code should be rewritten in another ways (when we call Dispose(), we may not close Flush()) :

--------------------------------------------------------------------

StreamWriter writer = new StreamWriter(filePath);
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
writer.Flush();
writer.Dispose();

--------------------------------------------------------------------

or, more correctly,

--------------------------------------------------------------------

StreamWriter writer = new StreamWriter(filePath);
try
{
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
}
finally
{
writer.Dispose();
}

--------------------------------------------------------------------

C# suggest statement "using" to call Dispose() method

--------------------------------------------------------------------

using (StreamWriter writer = new StreamWriter(filePath))
{
for (int i = 0; i < result.Length; i++)
{
writer.WriteLine(result[i].name + ": " + result[i].value);
}
}

--------------------------------------------------------------------

using Statement (C# Reference) http://msdn2.microsoft.com/en-us/library/yh598w02.aspx
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

No comments: