what using the ‘using’ block in c# does to your code


Let us take a simple console application which has the below code written in it

    class Program

    {

        static void Main(string[] args)

        {

            using (SqlConnection connection = new SqlConnection())

            {

                connection.Open();

                connection.Close();

            }

        }

    }

the IL that gets generated for the above program looks something like below...

        [0] class [System.Data]System.Data.SqlClient.SqlConnection connection)

    L_0000: ldnull

    L_0001: stloc.0

    L_0002: ldloc.0

    L_0003: callvirt instance void [System.Data]System.Data.Common.DbConnection::Open()

    L_0008: ldloc.0

    L_0009: callvirt instance void [System.Data]System.Data.Common.DbConnection::Close()

    L_000e: leave.s L_001a

    L_0010: ldloc.0

    L_0011: brfalse.s L_0019

    L_0013: ldloc.0

    L_0014: callvirt instance void [mscorlib]System.IDisposable::Dispose()

    L_0019: endfinally

    L_001a: ret

    .try L_0002 to L_0010 finally handler L_0010 to L_001a 

On analyzing this IL what we realize is that this code is nothing but syntactic sugar for the try-finally block shown below

SqlConnection connection = new SqlConnection();

try

{

    connection.Open();

    connection.Close();

}

finally

{

    if(connection != null)

        connection.Dispose();

} 

Overall a pretty neat feature to have...

Till my next post,

Regards,

AlD

Comments (2)
  1. Your exploration on IL is interesting.

  2. Alvaro Dias says:

    Thanks… glad you liked it.. will be posting more such blogs 🙂

Comments are closed.

Skip to main content