You can use the using statement in C# for ensuring that the object is disposed when it goes out of scope. The using statement provides an easy way for the user to save them from writing extra code for this scenario.
Take the below code snippet as an example where we use FileStream and StreamWriter objects. We might have to call the dispose method in the finally block as shown below.
FileStream fileStream = new FileStream("senthilkumar.txt", FileMode.Create); try { StreamWriter streamWriter = new StreamWriter(fileStream); try { streamWriter.WriteLine("This is a sample text"); } finally { ((IDisposable) streamWriter).Dispose(); } } finally { ((IDisposable) fileStream).Dispose(); }
The same can be written better with the using statement and yet ensuring that the object is disposed when it is out of scope.
using (FileStream fileStream = new FileStream("senthilkumar.txt", FileMode.Create)) { using (StreamWriter streamWriter = new StreamWriter(fileStream)) { streamWriter.WriteLine("This is a sample text"); } }
Note that the type must implement Idisposable interface when you want to use it within the using statement.If the type doesnot implement the interface , you will get an compiler error similar to this
type used in a using statement must be implicitly convertible to ‘System.IDisposable’