#432 – Initialize Multiple Objects in a using Statement

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.");
            }
Advertisements