Using Statements
From a completely unrelated Google search I came across this post by Fritz Onion over on pluralsight mentioning that he was happy to see Visual Basic 2005 adopting the C# using statement to make resource management a little easier in VB. He went on to concede that it wasn’t quite as elegant as the corresponding C#. Here is the VB example he provided:
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
And here is the C# version he compared it to:
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]);
}
}
I can’t help but point out that VB and C# have nothing on C++ when it comes to resource management. Here is the corresponding code written in C++:
SqlConnection conn(dsn);
SqlCommand cmd("SELECT * FROM Employees", %conn);
conn.Open();
msclr::auto_handle<SqlDataReader> rdr(cmd.ExecuteReader());
while (rdr->Read())
{
Console::WriteLine(rdr->GetValue(0));
}
Not only is this easier to write IMHO, but more importantly the code is correct by default. More on C++ in my upcoming book: Applied Visual C++ 2005. I’ve made a general rule for myself as I write the book that I should stay away from comparing C++ to other languages, with the exception of IL. So this blog helps me to vent.
:)
Don’t get me wrong. C# is a fun language which I’ve been forced to had the pleasure of using a fair amount over the last few years. It certainly has some language and compiler features (in version 2.0) that I wish we had in C++. VB on the other hand… [insert some Don Box crack about a semicolon-starved language].
© 2005 Kenny Kerr