0

What purpose does “using” serve when used the following way:-

ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS)

private Method(SqlConnection connection)
{
    using (SqlTransaction transaction = connection.BeginTransaction())
    {
        try
        {
            // Use the connection here
            ....

            transaction.Commit();
        } 
        catch
        {
            transaction.Rollback();
            throw;
        }
    }
}

OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}

I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code,

What if I omit it (I know the code will work) but what functionality will I be losing

Julien Lebosquain
  • 40,639
  • 8
  • 105
  • 117
user287745
  • 3,071
  • 10
  • 56
  • 99

5 Answers5

6

When you leave the using() block your connection will be closed or similar cleanup duties are performed. This is achieved by calling the object's Dispose() method.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • +1, Also this is called *using statement* compared to "using namespace" construct which is called *using directive* . – sharptooth Jun 17 '10 at 06:10
  • It also places that call in a finally block so that it will still be called should an exception be thrown. – Ed S. Jun 17 '10 at 06:11
5

Straight from MSDN:

using (Font font1 = new Font("Arial", 10.0f)) 
{
  byte charset = font1.GdiCharSet;
}

is equivalent with:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

It's a shorter and more concise way of saying: I want to use this thing I creates for all kinds of wonderful things, and I want the framework to clean up my playground when I'm done with it.

It's usually used with classes that allocate resources (Streams, Database connections...) because you might forget or neglect to free those resources when you are done with them. With using you don't concert yourself with resource management, and it's very likely that you won't leak resources.

P.S. The other using (as in using System.Web) is the using directive, the thing I'm talking about is the using statement.

SWeko
  • 30,434
  • 10
  • 71
  • 106
5

I think you are referring to two different usages of the using keyword.

When (generally) at the top of a file, it declares to import a namespace. See "using Directive".

using System.Collections;

namespace XYZ
{
}

When declared inside a function, it declares a limited lifetime and possibly scope (if declaring at the same time) for a variable such that it's IDisposable interface is automatically called after the block is closed. See "using Statement".

public void MyMethod()
{
    using (var conn = new SqlConnection(...))
    {
         // Do stuff
    }
}

Is the equivalient to:

public void MyMethod()
{
    SqlConnection conn;
    try
    {
        conn = new SqlConnection(...);
        // Do stuff
    }
    finally
    {
        conn.Dispose();
    }
}
Reddog
  • 15,219
  • 3
  • 51
  • 63
  • all answers are helpful, yours is the one i like, one question . ? Can i use a catch with this using using (var conn = new SqlConnection(...)) { // Do stuff } from the way its compiled i assume the catch outside using will give error, so what if its inside using? will that work like try catch finally! note:- i need to catch exceptions and display them on screen response.write......... – user287745 Jun 17 '10 at 06:39
  • and i shall mark ur answer as answer, when u answer this querry :-) thank you – user287745 Jun 17 '10 at 06:40
  • A little confused by your question, but here goes - Exceptions will still bubble up until they are caught yes. The 'using statemtnt' will merely allow you to limit the life of the `conn` variable. You can put your try/catch block inside the using block if you wish, or you can put the using block inside your try/catch. The only thing limiting the latter is that you won't have access to `conn` in the catch/finally blocks [not that you should need them anyways]. – Reddog Jun 17 '10 at 07:09
2

Behind the scenes, it wraps your code in a try/finally block, and in the finally block calls IDiposable.Dispose() ensuring any resources are cleaned up.

Basically it saves you the headache of doing:

SqlTransaction transaction = connection.BeginTransaction();

try
{ 
  //some code;
}
finally
{
  transaction.Dispose();
}
Alan
  • 45,915
  • 17
  • 113
  • 134
1

As Thief Master said - when the using block is exited the SQLTransaction or SQLConnection is closed. No matter if it exits through a return or by throwing an exception.

If you omit the using you have to close the transaction / connection by yourself. By use using the system does this for you automatically.

bernhardrusch
  • 11,670
  • 12
  • 48
  • 59