Entries:
Comments:
Posts:

Loading User Information from Channel 9

Something went wrong getting user information from Channel 9

Latest Achievement:

Loading User Information from MSDN

Something went wrong getting user information from MSDN

Visual Studio Achievements

Latest Achievement:

Loading Visual Studio Achievements

Something went wrong getting the Visual Studio Achievements

Are you a Using user?

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

Tag:

Follow the Discussion

  • RobRob

    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.

  • OosteekloOosteeklo

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

  • AnachosticAnachostic

    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.

Remove this comment

Remove this thread

close

Comments Closed

Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums,
or Contact Us and let us know.