C# Language Highlight: Using Keyword

Welcome to this installment of the .NET Nuts & Bolts column. The focus of this article will be on highlighting the C# using keyword. The using keyword has been in the language since the initial release. Something many developers do not realize is that the using keyword is a dual-purpose keyword. You'll touch on the common usage that C# developers should be familiar with, add a twist to it, and focus on the lesser known use that is valuable to understand.

Using Directive

Many readers will recognize the C# using keyword for its most common usage, which is to import types defined in namespaces into the scope of a code file. It is a directive when employed in this fashion. It adorns the top of a code file to import a namespace so that it can be used throughout the code file in more of a shorthand notation. Example code without the using directive:

namespace CodeGuru.Example
{
   class Program
   {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static string TestCfg()
      {
         return System.Configuration
            .ConfigurationSettings.AppSettings["MySetting"];
      }
   }
)

Here is the example from above refactored to demonstrate the using directive to import types:

using System.Configuration;

namespace CodeGuru.Example
{
   class Program
   {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static string TestCfg()
      {
         return ConfigurationSettings.AppSettings["MySetting"];
      }
   }
}

In addition to importing a namespace, the using directive can be used to create what is known as an alias. Aliasing allows you to assign an alternate name to use in place of a particular namespace. It looks syntactically similar to a variable declaration and assignment except it just denotes an alternate name to replace the namespace, not unlike the act of defining a synonym. The following example demonstrates a refactoring of the examples above to employ an alias for the System.Configuration.ConfigurationSettings namespace:

using cfg = System.Configuration.ConfigurationSettings;

namespace CodeGuru.Example
{
   class Program
   {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static string TestCfg()
      {
         // use of the cfg alias
         return cfg.AppSettings["MySetting"];
      }
   }
}

I personally will typically employ the using directive to import types and not bother with aliasing, but I know others who enjoy aliasing.

Using Statement

The dual purpose of the using keyword of which many C# developers are painfully unaware is employing using as a statement. When used as a statement, it defines a scope at the end of which a specific object will be disposed once the scope is exited. This may not seem earth shattering, but the first time that your application runs out of available database connections because a developer unknowingly wasn't closing and disposing a DataReader object it will become pretty clear pretty fast. The following sample code demonstrates a code mistake that I see all too often around use of DataReaders:

using System.Data;
using System.Data.SqlClient;
using cfg = System.Configuration.ConfigurationSettings;

namespace CodeGuru.Example
{
   class Program
   {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static void TestCfg()
      {
         string connectString =
            cfg.AppSettings["ConnectionString"];
         string query =
            "Select * from Northwind";
         SqlConnection connection =
            new SqlConnection(connectString);
         SqlCommand command = new SqlCommand(query, connection);
         IDataReader reader = null;
         try
         {
            reader = command.ExecuteReader();
            while (reader.Read())
            {
               // Some processing stuff here
            }

            // Works great as long as we are on a happy path
            // with no errors
            reader.Close();
         }
         catch (SqlException e)
         {
            // Some error handling stuff here
         }
      }
   }
}

C# Language Highlight: Using Keyword

Here is an example of refactoring the code example above to include the proper try/finally construct the original example should have used as a best practice to ensure proper disposal of the database objects:

using System.Data;
using System.Data.SqlClient;
using cfg = System.Configuration.ConfigurationSettings;

namespace CodeGuru.Example
{
   class Program
    {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static void TestCfg()
      {
         string connectString =
            cfg.AppSettings["ConnectionString"];
         string query =
            "Select * from Northwind";
         SqlConnection connection =
            new SqlConnection(connectString);
         SqlCommand command = new SqlCommand(query, connection);
         IDataReader reader = null;
         try
         {
            reader = command.ExecuteReader();
            while (reader.Read())
            {
               // Some processing stuff here
            }
         }
         catch (SqlException e)
         {
            // Some error handling stuff here
         }
         finally
         {
            // Make sure we close and clean up after ourselves!
            if (reader != null) reader.Dispose();
            if (command != null) command.Dispose();
            if (connection != null) connection.Dispose();
         }
      }
   }
}

Here is an example of refactoring the code example above to include a using statement that governs automatic disposal of the DataReader instance once the scope in which it is declared is exited for any reason. That includes whether an exception should occur.

using System.Data;
using System.Data.SqlClient;
using cfg = System.Configuration.ConfigurationSettings;

namespace CodeGuru.Example
{
   class Program
   {
      static void Main(string[] args)
      {
         Program.TestCfg();
      }

      public static void TestCfg()
      {
         string connectString =
            cfg.AppSettings["ConnectionString"];
         string query = "Select * from Northwind";
         SqlConnection connection =
            new SqlConnection(connectString);
         SqlCommand command =
            new SqlCommand(query, connection);

         try
         {
            // Reader is automatically disposed when exits
            // using scope
            using (IDataReader reader = command.ExecuteReader())
            {
               while (reader.Read())
               {
                  // Some processing stuff here
               }
            }
         }
         catch (SqlException e)
         {
            // Some error handling stuff here
         }
      }
   }
}

The using statement certainly can lead to a reduction in code, but the main advantage is helping to ensure that objects are properly disposed when they exit scope. This can help prevent unfortunate occurrences of very difficult to isolate defects where items aren't properly disposed.

Summary

This article covered the C# using keyword employed as a directive and as a statement. The dual-purpose nature of the using keyword is a powerful feature of C# that is often overlooked or under used. Hopefully, the common examples above gave you have an appreciation of the power if its duality and you can employ them successfully within your code to the betterment of unmanaged object cleanup.

Future Columns

The topic of the next column is yet to be determined. It is likely that I will cover lazy loading of the AJAX TabContainer control. If you have something in particular that you would like to see explained here, you could reach me at mstrawmyer@crowechizek.com.



About the Author

Mark Strawmyer

Mark Strawmyer is a Senior Architect of .NET applications for large and mid-size organizations. He specializes in architecture, design and development of Microsoft-based solutions. Mark was honored to be named a Microsoft MVP for application development with C# for the fifth year in a row. You can reach Mark at mark.strawmyer@crowehorwath.com.

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • IBM Worklight is a mobile application development platform that lets you extend your business to mobile devices. It is designed to provide an open, comprehensive platform to build, run and manage HTML5, hybrid and native mobile apps.

  • Companies must routinely transfer files and share data to run their business, work with partners, and speed operations. However, many find the traditional approach to file transfer lacks necessary security, is too complex and difficult to manage, does not support the levels of automation needed, and breaks down when addressing the file transfer requirements of new areas like Big Data analytics and mobile applications. This QuinStreet SmartSelect discusses how the changing business environment is making the use …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds