#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

4 Responses to #432 – Initialize Multiple Objects in a using Statement

  1. Pingback: Multiple Objects in Using block [TIP] « My curious world in bits and bytes

  2. kai zhou says:

    Thank you Sean.

  3. 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();
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: