Using Statement and Dispose Method in C# and VB.NET






3.40/5 (5 votes)
Using Statement and Dispose Method in C# and VB.NET
Since .NET 2.0, we are aware of using
statement to perform resource intensive operations like database operations, file IO operations, etc. Using
statement basically marks a boundary for the objects specified inside using ()
braces. So when code block using (){}
(in C#) or Using
– End Using
(in VB.NET) is exited either after normal execution or some exception cause, the framework invokes the Dispose
method of these objects automatically. Before creating or using any object inside using
block, one must make sure that the object type implements the IDisposable
interface.
We can specify multiple objects inside using
-block, and also write using
-blocks in stack as shown in the example below.
public class DotNetTips
{
private void DoSomeOperation()
{
using (SqlConnection con1 = new SqlConnection("First Connection String"),
con2 = new SqlConnection(("Second Connection String"))
{
// Rest of the code goes here
}
}
private void DoSomeOtherOperation()
{
using (SqlConnection con = new SqlConnection("Connection String"))
using (SqlCommand cmd = new SqlCommand())
{
// Rest of the code goes here
}
}
}
Using
statement is useful when we have to call dispose
method multiple times on different objects. Otherwise, we will have to call Dispose
method on each object as:
if (con != null) con.Dispose();
if (cmd != null) cmd.Dispose();
When the using
block code compiles to intermediate language, it translates the using
statements into equivalent try
/finally
block.
I hope this tip can be useful for all.
Posted in .NET Technologies, C#/VB.NET, CodeProject, Dot NET Tips Tagged: .NET 3.5, C#, Dispose, Using Statement
