Search code examples
c#sqlconnectionusing-directives

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


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


Solution

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