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?
using
statements like that.using
permits only one type, even if you are initializing multiple resources in the same statement. If you are using multiple statements or multiple types, by definition you must nestusing
statements; here, the objects are different types and must be in separateusing
statements. – Giousing (MemoryStream ms1 = new MemoryStream(), ms2 = new MemoryStream()) { }
. I mean like this where you can redefine the type:using (MemoryStream ms = new MemoryStream()) using (FileStream fs = File.OpenRead("c:\\file.txt")) { }
– Ericerica