Power of the Using Statement
January 25th, 2007 by admin | No Comments | Filed in .NET, Database, Design, MobileWhere is the best place to Close() a SqlConnection? What about to Dispose() a SqlDataAdapter?
I was writing on some code yesterday when I started getting this compile warning message: (Code displayed below)
Warning 35 Variable ’scon’ is used before it has been assigned a value. A null reference exception could result at runtime.
I said to myself… “Self, this is just a warning… move on.”
As the quantity of warning messages kept growing… I could not take it any more. I had to get ride of those warning messages.
Now… How to do it? I know… Ask Chris Craft, that is what I will do. He explained about the using statement and then sent me this great link.
He explained, that when using the using (sounds weird), after the using statement is finished, the objects will be closed and disposed automatically.
WOW!!! Here is the before and after.
Initial code:
Dim scon As SqlConnection
Dim sda As SqlDataAdapter
Dim scmd As SqlCommand
Dim ds As New DataSet
Dim sql As String = “SELECT * FROM MyTable”Try
scon = New SqlConnection(constring)
scmd = New SqlCommand(sql, scon)
scmd.CommandType = CommandType.Text
sda = New SqlDataAdapter(scmd)
sda.Fill(ds, “Blah“)
Catch e As Exception
Throw e
Finally
sda.Dispose() ‘Was giving the warning
scmd.Dispose() ‘Was giving the warning
scon.Close() ‘Was giving the warning
End Try
Code using the using:
Dim ds As New DataSet
Dim sql As String = “SELECT * FROM MyTable”Try
Using scon As SqlConnection = New SqlConnection(constring)
Using scmd As SqlCommand = New SqlCommand(sql, scon)
scmd.CommandType = CommandType.Text
Using sda As SqlDataAdapter = New SqlDataAdapter(scmd)
sda.Fill(ds,”Blah“)
End Using
End Using
End Using
Catch e As Exception
Throw e
Finally
End Try
The code using the using looks neater, cleaner, and has no warning messages.

