Using statements are used to define a scope on an object that implements the iDisposable interface. It automatically calls the Dispose method on the object when it goes out of scope.
Here's a neat little trick to deal with nested using statements. Consider the following code snippet that has a couple of them:
using (FileStream fs = File.Create("File.txt"))
{
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("The content of my file!");
}
}
Here's a cleaner, and in my opinion easier, way to write these. Notice that the FileStream object is useable when creating the TextWriter object.
using (FileStream fs = File.Create("File.txt"))
using (TextWriter tw = new StreamWriter(fs))
{
tw.WriteLine("The content of my file!");
}
If you are instantiating multiple objects of the same type, you could put them all on one line. It is harder to read this way, but maybe that's just me. ;)
using (StreamWriter tw1 = File.CreateText("W1"), tw2 = File.CreateText("W2"))
{
tw1.WriteLine("The content of my first file!");
tw2.WriteLine("The content of my second file!");
}
No comments:
Post a Comment