I've recently been forced to had the pleasure of writing a fair amount of code in VB.NET 2.0, and one thing I was happy to see was the introduction of the 'Using' statement. You can now write code that uses disposable resources without having to author your own Try/Finally blocks, just like in C#. The canonical data access with ADO.NET will now look something like:
Using conn As New SqlConnection(dsn)
Using cmd As New SqlCommand("SELECT * FROM Employees", conn)
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
While rdr.Read()
Console.WriteLine(rdr(0))
End While
End Using
End Using
End Using
Kind of has a nice symmetry to it, doesn't it? Of course you still can't quite achieve the elegance of the C# using block which, because of the scoping rules of C#, can be stacked without additional braces (or End Using statements):
Update: corrected lack of rdr.Read().
using (SqlConnection conn = new SqlConnection(dsn))
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn))
{
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
Console.WriteLine(rdr[0]);
}
}
Posted
Apr 28 2005, 02:34 PM
by
fritz-onion