hadn't seen 'using' here before

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hey all,

i've never seen "using" in the following context before, could someone
please explain:

static void Main()
{
string queryString =
"SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection = GetConnectionString())
{
...

}

thanks,
rodchar
 
rodchar said:
i've never seen "using" in the following context before, could someone
please explain:

static void Main()
{
string queryString =
"SELECT CategoryID, CategoryName FROM dbo.Categories;";
using (SqlConnection connection = GetConnectionString())
{
...

}

The "using" statement is basically a try/finally block which calls
Dispose on whatever you create in the ( ) part. So the above is (very
roughly) equivalent to:

SqlConnection connection;
try
{
connection = = GetConnectionString();
....
}
finally
{
if (connection != null)
{
connection.Dispose();
}
}
 
rodchar said:
i've never seen "using" in the following context before, could someone
please explain:
using (SqlConnection connection = GetConnectionString())
{

It's a shorthand for creating the connection in a try...finally block,
and calling connection.Dispose() in the "finally" section. "using" can be
used in this way with any class that implements IDisposable (such as
SqlConnection) to ensure that Dispose gets called, while keeping the source
code clean and readable.
 
Thank you all for the help.

Alberto Poblacion said:
It's a shorthand for creating the connection in a try...finally block,
and calling connection.Dispose() in the "finally" section. "using" can be
used in this way with any class that implements IDisposable (such as
SqlConnection) to ensure that Dispose gets called, while keeping the source
code clean and readable.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top