#431 – The using Statement Automates Invocation of the Dispose Method

A class may implement the IDisposable interface, providing a Dispose method, to allow for deterministic destruction.  Client code calls Dispose when it is done using the object, telling it to release resources that it might be holding.

It can be hard to ensure that you always call Dispose when appropriate, especially when exceptions occur.

The using statement in C# specifies the scope in which you want to use an object and guarantees that the Dispose method will be called when the object goes out of scope.

            using (StreamWriter writer =
                new StreamWriter(@"D:\Remember.txt"))
            {
                writer.Write("RIP Steve Jobs, 1955-2011");
            }

If we look at the IL generated for the using statement, we can see that it is converted to a try/finally block and the Dispose method of the StreamWriter object is called in the finally block.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #431 – The using Statement Automates Invocation of the Dispose Method

  1. zenwalker says:

    Thats nice article btw sean. I almost every day follow your blog for updates.
    Any ways, i had written similar article on the same topic but in a different way, check it out if you care 2 http://adventurouszen.wordpress.com/2011/10/03/proving-using-block-is-try-finally-in-il/

  2. Pingback: #673 – Types Used in using Statement Must Implement IDisposable « 2,000 Things You Should Know About C#

  3. Pingback: #910 – One Example of a finally Block | 2,000 Things You Should Know About C#

  4. Pingback: #941 – Checking to See If Objects Are Disposable | 2,000 Things You Should Know About C#

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 )

Connecting to %s

%d bloggers like this: