Nick Vaccaro
Nick Vaccaro

Reputation: 5504

C#: Initializing a variable with "using"

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.

Upvotes: 5

Views: 435

Answers (5)

Dathan
Dathan

Reputation: 7446

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();
}

Upvotes: 6

womp
womp

Reputation: 116977

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.

Upvotes: 8

kemiller2002
kemiller2002

Reputation: 115488

After the using statement it will exit the scope which it is available in. The objects Dispose method will be called, but the object won't necessarily be garbage collected at that time.

So what this means is that if you have items which are cleaned up (files closed etc.) in the object's Dispose() method, they will get cleaned up immediately after the using statement ends. If you have a finalizer (~YourClassName) in addition to this which does other things, you cannot guarantee that will get called at that time.

Upvotes: 0

Michael Stum
Michael Stum

Reputation: 180954

using is a language construct that takes an IDisposable and calls Dispose() on it.

So

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

is roughly equivalent to

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

Upvotes: 2

JSBձոգչ
JSBձոգչ

Reputation: 41378

When the sqlConnection variable goes out of scope (at the end of the bracketed block), the Dispose() method will automatically be called.

Upvotes: 0

Related Questions