Editorials

Dot Net Basics We Take for Granted

Dot Net Basics We Take for Granted

The USING clause in C# can be a great timesaver. As most know, enclosing the creation of an object in a USING Statement causes the dispose method to be called on that object automatically without any effort on the part of the coder. So, any object supporting IDisposable is a candidate to be enclosed in a USING construct.

I especially like to see USING when working with database objects such as a connection or command. With opening a database connection using connection pooling, the default method for connecting to a database in ADO.Net, if you don’t close the connection correctly, it remains open in the connection pool, reducing performance against your database by not re-using open connections in the pool as you should. Opening a database connection in a USING statement assures that the connection is properly returned to the connection pool for the next consumer.

I know these things and try to use them as often as is practical. However, some objects are not designed to be used with a USING statement because they do not inherit from IDisposable. A HttpWebRequest object is an example. However, an HTTPWebResponse object can be used in a USING statement.

Today I was resolving a bug on an application where the client would call the web server and work fine for the first three or four attempts. After that, each web request would simply timeout. With some research I found the issue was that I was not disposing of my HttpWebResponse object. Placing that in a USING statement completely resolved my issue.

The moral of the story is to clean up your variables. If you can use the USING statement, you have confidence that your variables are cleaned up according to the deign of the class.

Cheers,

Ben