Maybe it is a trival question, but it\'s bothering me. And don\'t shout laud if it is a duplicate - I tried to search, but there are so many questions regarding using that i
You have a constructor for StreamWriter (NET Framework 4.5 only) that allows specifying the leaveOpen
boolean that defines whether your instance takes ownership of the underlying stream or not.
If not specified (as in your example, or for previous versions of the framework), by default it's false
, so closing (or disposing) the instance closes the underlying stream.
Unless you set the leaveOpen parameter to true, the StreamWriter object calls Dispose() on the provided Stream object when StreamWriter.Dispose is called.
So there is no difference between both pieces of code you provided.
Use {} always! It makes the intention of your code a lot better. Your code looks like:
using (IsolatedStorageFile ISF = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("example.txt", FileMode.Create, ISF)))
{
writeFile.WriteLine("Example");
}
}
You can then see that the StreamWriter is executed in the context of the ISF. If I understand the ISF correctly, the ISF should not be closed when the Streamwriter closes the file. And you could open another File in the ISF Block.
Once it leaves the using block, Dispose is called.
using Statement (C# Reference)
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.
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
Your stream remains open even though the stream writer is disposed of. You could, for example, open another stream writer and continue writing to the stream.