IDisposable Interface
Before looking into using statement, we need to have a look at IDisposable interface.
IDisposable interface (when implemented) signals users of this class that it offers a public method (Dispose()) that can be called to deterministically close the resource.
IDisposable Definition:
public interface IDisposable { void Dispose(); }
When your class implements the object's Dispose or Close method, it's highly recommended to keep then in the finally block, so it's guaranteed that the dispose or close method called
public static void Main() { try { SQLConnection connection = new SQLConnection(ConnstringString); ... } finally { if (connection != null) { // better to check for the connection state before closing it connection.close(); connection.dispose(); } } }
Using Statement in C#
Adding an exception handling code is always the best thing to do. Fortunately C# has given us the using statement, which offers an identical alternate to the above. So rewriting the above code.
public static void Main() { using (SQLConnection connection = new SQLConnection(ConnstringString)) { ... } }
In the using statement, we actually initialize an object and save its reference in a variable or use a preintializ. Then we access the variable via code contained inside using's braces. When this code gets compiled, the compiler automatically emits the try and finally blocks (No Catch block is included).
The object intialized above need to be an IDisposable implementation, because inside the generated finally block, the compiler emits code to cast the object to an IDisposable and calls the Dispose method. So it's obvious, that the compiler allows the using statement to be used only with types that implement the IDisposable interface.
Also Inside the using statement we can intialize multiple variables, provided all the variables of same type.
Happy Coding !!!
|
No responses found. Be the first to respond and make money from revenue sharing program.
|