Assuming you have created a Class in your system. Which is an appropriate way of notifying the class that the object is going out of scope?
By implementing the IDisposable interface, we will be forced to implement the Dispose method which can handle the notification and dispose the objects using unmanaged resources. The Using block will ensure that the Dispose method will get called at the end of the block. Otherwise another approach is that you would need to implement the Dispose method and call it manually right before the object went out of scope, which is partially correct, does not handle the problem of exceptions. If you wanted to use second approach you would have to call the Dispose method in a finally block using the try/catch/finally mechanism, which is, in fact, what the using block does for you.
Below both approaches are explained in detailed:-
First approach using “Using” keyword :-
Using provides a convenient syntax that ensures the correct use of IDisposable objects.
The following example shows how to use the using statement.
using (Font font1 = new Font("Arial", 10.0f))
{
byte charset = font1.GdiCharSet;
}
File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.
As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.
Second approach using try/catch/finally mechanism:-
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time.
Font font1 = new Font("Arial", 10.0f);
try
{
byte charset = font1.GdiCharSet;
}
finally
{
if (font1 != null)
((IDisposable)font1).Dispose();
}