Home > .NET Development > Why using the using keyword instead of try/finally

Why using the using keyword instead of try/finally

I was confused that they both accomplish the same mission, then why using ?!

Maybe with using I’ll write less lines of code..
Maybe with using I’ll write more maintainable code..

Well, That’s true. Let’s take an example of disposing a SqlConnection object,

This is the way you do it with try finally, the compiler won’t get out of the method blocks to return the value unless it executes the finally block to ensure closing the connection.

        private static string GetString2(string connectionString)
        {
            SqlConnection connection = null;
            SqlCommand cmd = null;

            try
            {
                connection = new SqlConnection(connectionString);
                cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT StringColumn FROM SomeTable";
                connection.Open();
                return Convert.ToString(cmd.ExecuteScalar());
            }
            finally
            {
                connection.Close();
            }
        }

Well, with using the compiler won’t get out of the using block unless it executes the Dispose() method on the resource object if it serves the IDisposable interface.

        private static string GetString(string connectionString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand cmd = connection.CreateCommand();
                cmd.CommandText = "SELECT StringColumn FROM SomeTable";
                connection.Open();
                return Convert.ToString(cmd.ExecuteScalar());
            }
        }

Have you noticed any differences? This is the Code Metrics,
Code Metrics

So, how can I benefit from the using keyword to automatically free my resources when my object gets disposed?
Simply implement the IDisposable interface in your class, and use your class inside the using block.

    class Program
    {
        static void Main()
        {
            using (MyClass myClass = new MyClass())
            {

            }

            throw new InvalidOperationException();
        }
    }

    public class MyClass : IDisposable
    {
        public void Dispose()
        {
            throw new NotImplementedException();
        }
    }

And off course the NotImplementedException will fire before the InvalidOperationException.

Hope this makes sense, Thanks!

Advertisements
Categories: .NET Development
  1. April 23, 2009 at 10:30 pm

    Nice Issy, keep it up 🙂

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: