#431 – The using Statement Automates Invocation of the Dispose Method
October 12, 2011 4 Comments
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.
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/
Pingback: #673 – Types Used in using Statement Must Implement IDisposable « 2,000 Things You Should Know About C#
Pingback: #910 – One Example of a finally Block | 2,000 Things You Should Know About C#
Pingback: #941 – Checking to See If Objects Are Disposable | 2,000 Things You Should Know About C#