Are you a Using user?

Sign in to queue



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.


using (SqlConnection cn = new SqlConnection(sConnString)) { ... }
Using cn As New SqlConnection(sConnString)
End Using



The Discussion

  • User profile image

    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.

  • User profile image

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

  • User profile image

    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.

Add Your 2 Cents