Search code examples
c#ado.netusing

c# using statements without semicolon


I found following code online:

using (SqlConnection con = new SqlConnection(connectionString))
    {
        //
        // Open the SqlConnection.
        //
        con.Open();
        //
        // The following code uses an SqlCommand based on the SqlConnection.
        //
        using (SqlCommand command = new SqlCommand("SELECT TOP 2 * FROM Dogs1", con))
        using (SqlDataReader reader = command.ExecuteReader())
        {
        while (reader.Read())
        {
            Console.WriteLine("{0} {1} {2}",
            reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
        }
        }
    }

can anyone explain me why using (SqlCommand ..) doesn't end with semicolon. my second question is generally after using we have to have { } to indicate scope of that using variable why in this case it is missing? and how, when will it dispose command object?


Solution

  • can anyone explain me why using (SqlCommand ..) doesn't end with semicolon

    Because the using command will run exactly one block: the one that follows. That block can be one statement only. If you put a semicolon at the end it will do nothing (run an empty statement).

    This is the same case with 'if' for example.

    if(a==b)
       Console.Write("they are equal!");
    
    Console.Write("I'm outside the if now because if only runes one block");
    

    But

    if(1==2);
    Console.Write("I will always run because the if ends with a semicolon! (executes an empty statement)");
    

    my second question is generally after using we have to have { } to indicate scope of that using variable why in this case it is missing?

    It's not, look closer.

    and how, when will it dispose command object?

    It will call object.Dispose() (if it's not null) when the block ends (even if it throws an exception).