One of the shortcuts of C# (And now in VB.NET 2005) I love is the using statement. For those not familiar with it, it allows you to create objects within the scope of the using block and then once the block completes execution, calls the Dispose method on all the specified objects if they implement IDisposable. This occurs even if an exception is thrown. From what I understand, the using block in the resulting IL is a try/finally block, where the object disposal takes place in the finally.
This is perfect for working with a DataReader and instances where we want to make sure a database connection is closed right after a call. Since the Dispose method on a DataReader and Connection object call their own Close method they will be implicitly closed when we exit the using block, regardless of errors.
string ConnectionString = "server=127.0.0.1;database=duwamish7vb;Trusted_Connection=true";using (SqlConnection Conn = new SqlConnection(ConnectionString)){ Conn.Open(); SqlCommand Command = new SqlCommand("SELECT Name FROM Authors",Conn); using (SqlDataReader Reader = Command.ExecuteReader()) { Authors.DataTextField = "Name"; Authors.DataSource = Reader; Authors.DataBind(); } Command = new SqlCommand("SELECT Subject FROM Books", Conn); using (SqlDataReader Reader = Command.ExecuteReader()) { Books.DataTextField = "Subject"; Books.DataSource = Reader; Books.DataBind(); }}