Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Initializing a variable with "using"

Tags:

c#

In regards to the following code:

using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
  code...
}

Is the SqlConnection initialized with "using" so it is dereferenced/destructed after the brackets?

Please correct my questioning where necessary.

like image 794
Nick Vaccaro Avatar asked Dec 15 '09 18:12

Nick Vaccaro


2 Answers

using is a syntactical shortcut for correctly calling Dispose() on the object.

After the code in the braces is finished executing, Dipose() is automatically called on the object(s) wrapped in the using statement.

At compile time, your code above will actually be expanded to

{
  SqlConnection sqlConnection = new SqlConnection(connectionString);
  try
  {
    // .. code
  }
  finally
  {
    if (sqlConnection!= null)
      ((IDisposable)sqlConnection).Dispose();
  }
}

You can see how it's a handy shortcut.

like image 152
womp Avatar answered Sep 27 '22 21:09

womp


Yes. The using statement is just syntactic sugar, and is translated by the compiler into something like

SqlConnection sqlConnection;
try
{
  sqlConnection = new SqlConnection(connectionString);
  // code...
}
finally
{
  if (sqlConnection != null)
     sqlConnection.Dispose();
}
like image 36
Dathan Avatar answered Sep 27 '22 20:09

Dathan