Are you a Using user?

Published 04 September 07 11:37 AM | Coding4Fun 

crime-scene-clean-up-8[1]

Over at Angry Coder, the talk about the "Using" block.  This is something coders should use if possible since it helps do object cleanup for items like GDI+ (Graphics) and connections (streams, files, ...).  It helps define when the object leaves scope and helps close streams, clear up memory, reset defaults, ... when you're done with that object automatically!  You can make your own objects able to use the Using block just by implementing the IDispose interface by adding in the Dispose() method.  It helps clean up so you don't have to.

Here is a quick example of a using block with a SqlConnection object.  If you ever wondered what gets called in that Dispose method but don't have access to the source, use Reflector to verify.

C#

using (SqlConnection cn = new SqlConnection(sConnString)) { ... }
VB.Net
Using cn As New SqlConnection(sConnString)
  ...
End Using
Filed under:

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Rob said on September 4, 2007 4:59 PM:

The using block is ok but promotes ignoring resource allocation errors and also promote handling errors at a scope higher than where the error occurred.   Generally, error handling far away from the thing that caused the error is a sign of poor quality.

# Anachostic said on September 5, 2007 9:01 PM:

I do not "use".  I'm still old-fashioned in that I Dim all my variables at the beginning of the method, instantiate them just before use, then clean them up in a Finally block.  In For..Next loops, I will use a inline, temporary, transient, (whatever you call it) variable, but that's the extent of it.

I think the new design of declaring just before use makes code harder to read.  During a code review, when all the variables are in the beginning, you can look at a method and say: "Ok, this uses a SQLConnection, SQLCommand, and SQLDataReader."  It mentally prepares you for reviewing the code.  Or you may see 20 variables declared and immediately think, this needs to be refactored.

# Oosteeklo said on September 6, 2007 3:09 AM:

Yes, I find it a very useful tool, especially for databaseconnections, where things can get dirty when exeptions occur.

Leave a Comment

(required) 
(optional)
(required) 
Page view tracker