Use the “using” statement on objects that implement the IDisposable Interface
Posted
by mbcrump
on Geeks with Blogs
See other posts from Geeks with Blogs
or by mbcrump
Published on Mon, 03 May 2010 15:30:28 GMT
Indexed on
2010/05/03
22:39 UTC
Read the original article
Hit count: 208
From MSDN :
C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
In my quest to write better, more efficient code I ran across the “using” statement. Microsoft recommends that we specify when to release objects. In other words, if you use the “using” statement this tells .NET to release the object specified in the using block once it is no longer needed.
- private static string ReadConfig()
- {
- const string path = @"C:\SomeApp.config.xml";
- using (StreamReader reader = File.OpenText(path))
- {
- return reader.ReadToEnd();
- }
- }
- private static string ReadConfig1()
- {
- StreamReader sr = new StreamReader(@"C:\SomeApp.config.xml");
- try
- {
- return sr.ReadToEnd();
- }
- finally
- {
- if (sr != null)
- ((IDisposable)sr).Dispose();
- }
- }
© Geeks with Blogs or respective owner