The "USING" Statement in C#
At first most people think the using statement is the
direct equivialant to VB.NET's import statement.
Using System.IO;
is the same as
imports System.IO
But it is not.
The using statement is one of coolest features of C# (and
NOW VB.NET).
For those of us who believe in "Aquire Late and Release Early"
for our database connections the using statement has been
our way of managing connections to the database and memory
resources.
The using statement get translated behind the scenes in C#
and .NET framework. These are acquisition, usage, and
disposal.
Important Disclaimer... The object resource has to
implement IDisposable interface.
For example in C# for a object that suipport IDisposable
we would write it as such.
using (MyResource myRes = new MyResource())
{
myRes.DoSomething();
}
Which basically get transalated in the CLR and MISL to
something that works like this.
MyResource myRes= new MyResource();
try
{
myRes.DoSomething();
}
finally
{
// Check for a null resource.
if (myRes!= null)
// Call the object's Dispose method.
((IDisposable)myRes).Dispose();
}
This basically allows us to manage the memory resources
while managing our object life cycle ourselves versus the
Garbage Collector (GC).
What does this really do for us?
Lets look at database access scenario where we could use
the using statement is :
string connString = "Data Source=localhost;Integrated " +
"Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ID, Name FROM Customers";
conn.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine("{0}\t{1}", dr.GetString(0),
dr.GetString(1));
}
}
At first glance you might be thinking "Bad Ronnie" because
it looks like I didn't close my connection amoung other
things. BUT in reality I did. When we went out of the
scope of each of the two using blocks the objects
implementing IDisposable closed and disposed of their
resources.
This makes for cleaner, more compact and not to mention
readable code.
Now what about VB.NET, it uses object with IDispoable in
them but doesn't have the using statement.
To implement in Visual Basic 2003 under framework 1.1 (I'm
borrowing this code from a Microsoft PPT) you would have
to write your code like this.
Dim p As Pen = New Pen(c)
Try
g.DrawLine(p, 0, 0, 50, 50)
Finally
If Not p Is Nothing Then
CType(p, IDisposable) _
.Dispose()
End If
End Try
But now in Visual Basic 2005 under framework 2.0 you have
the using statement now. And thus would write your code
like this.
Using p As New Pen(c)
g.DrawLine(p, 0, 0, 50, 50)
End Using
Pretty clean code huh?
Happy Coding!!
The Ron
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home