Classes such as Stream
, StreamReader
, StreamWriter
etc implements IDisposable
interface. That means, we can call Dispose()
method on objects of these classes. They've also defined a public
method called Close()
. Now that confuses me, as to what should I call once I'm done with objects? What if I call both?
My current code is this:
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader(responseStream))
{
using (StreamWriter writer = new StreamWriter(filename))
{
int chunkSize = 1024;
while (!reader.EndOfStream)
{
char[] buffer = new char[chunkSize];
int count = reader.Read(buffer, 0, chunkSize);
if (count != 0)
{
writer.Write(buffer, 0, count);
}
}
writer.Close();
}
reader.Close();
}
}
As you see, I've written using()
constructs, which automatically call Dispose()
method on each object. But I also call Close()
methods. Is it right?
Please suggest me the best practices when using stream objects. :-)
MSDN example doesn't use using()
constructs, and call Close()
method:
Is it good?