Sunday, June 9, 2013

Advantages of using Statement in C#

We know that classes using un-managed resources should implement the IDisposable interface, override the Dispose() method and clear all the un-managed resources in the Dispose() method. Even if all these are done properly, what if the code using the object does not call the Dispose() method, the un-managed resources will remain in memory till Garbage Collection runs and clears them.

Whenever we use a class which implements the IDisposable interface, we should make sure that we call the Dispose() method of the class after using the object of the class. But we might at time forget to call the Dispose() method and this will hold the um-managed resources in memory till Garbage Collection runs. The using statement helps us avoid these situations by calling the Dispose method automatically.

The following example explains on how to use the using statement.

using (TextWriter objTw = File.CreateText("Using.txt"))
    objTw.WriteLine("Advantages of using Statement");

When the above line of code gets executed, the Dispose() method of the object objTw is automatically once the code block completes executing. Using this convention makes sure that the Dispose() method is always called to free un-managed resources.

Make sure that your use the using statement only to initialize objects which implement the IDisposable interface, trying to use this statement for objects which do not implement might cause an error as an attempt will be made to call the Dispose() method of the object once the code execution gets completed, if the method does not exist then an error occurs.

Search Flipkart Products:

No comments: