#432 – Initialize Multiple Objects in a using Statement
October 13, 2011 4 Comments
The using statement defines the scope in which an object can be used, automatically calling the object’s Dispose method when it goes out of scope.
You can declare and initialize more than one object in a using statement, as long as they are all the same type. All of the objects will be disposed when the scope of the using statement ends.
using (StreamWriter writer = new StreamWriter(@"D:\Remember.txt"), writer2 = new StreamWriter(@"D:\Legacy.txt"), writer3 = new StreamWriter(@"D:\Clothing.txt")) { writer.Write("RIP Steve Jobs, 1955-2011"); writer2.Write("Apple II, Macintosh, iMac, iPhone, iPad"); writer3.Write("Jeans. Turtleneck."); }
Pingback: Multiple Objects in Using block [TIP] « My curious world in bits and bytes
Thank you Sean.
How to use…C# Using Statement
Brian
I also commonly group related using statements (that initialize different types). For example, database operations usually come in pairs or threes. They can all share the same block like this:
using (Connection conn = CreateConnection(…))
using (Command cmd = conn.CreateCommand(…))
using (var reader = cmd.ExecuteReader())
{
DoStuff();
}