October 1, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

C# Language Highlight: Using Keyword

  • January 30, 2008
  • By Mark Strawmyer
  • Send Email »
  • More Articles »

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, MCSD, MCSE, MCDBA is a Senior Architect of .NET applications for large and mid-size organizations. Mark is a technology leader with Crowe Chizek in Indianapolis, Indiana. He specializes in the 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 mstrawmyer@crowechizek.com.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel