Are you a Using user?
- Posted: Sep 04, 2007 at 8:37 AM
- 6 Views
- 3 Comments
Loading User Information from Channel 9
Something went wrong getting user information from Channel 9
Loading User Information from MSDN
Something went wrong getting user information from MSDN
Loading Visual Studio Achievements
Something went wrong getting the Visual Studio Achievements
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
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.
Follow the Discussion
Oops, something didn't work.
What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in. You need to be signed in to Channel 9 to use this feature.What does this mean?
Following an item on Channel 9 allows you to watch for new content and comments that you are interested in and view them all on your notifications page.sign up for email notifications?
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.
Yes, I find it a very useful tool, especially for databaseconnections, where things can get dirty when exeptions occur.
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