Using Blocks are new to VB’ers, what are the rules?

Using blocks are new to us VB developers. I get the basic concept – it’s cleaner than try/catch/finally blocks when all you are doing is disposing an object and it’s super great when dealing with unmanaged resources and good ol’ SqlConnections.

But the intricacies of using it are a little less obvious. Luckily, this code construct has been around in C# (and I will guess C++??) so we can learn from those folks.

I was trying to find a better way to deal with a file stream and memory stream today. Porting some code over from vs2003 to vs2005, the compiler was moaning about the following code block (I am only writing it loosely here…) where I am passing in a file name, opening up the file into a streamReader and then doing something to the streamreader and then closing both objects at the end. Maybe it wasn’t written perfectly to begin with, but the compiler issue was a new one.

dim fs as new FileStream(myfilename,FileMode.Open)
dim sr as new StreamReader

Try
   myStreamReader=new StreamReader(fs)

  … do some stuff

Catch exS as IOException
 … do something
Catch ex as Exception
 .. do something
Finally
   If  Not fs is nothing then
      fs .Close
  EndIf
  If Not sr is Nothing then
     sr.Close
  End If
End Try

So when I ported this to VS2005, the compiler was not happy about accessing the streamReader in the Finally block because it was possible that no value would be assigned and I’d get a null ref exception (on the bold red line.)

I knew that I could get rid of those Close methods with a using block but was not sure if nesting them was a) possible b) good code or c) something that would bite me in the rear down the road.

Once I figured out what I was dealing with: “nested using blocks” I quickly found this blog post by Scott Hanselman, who specifically says in the comments of this post that he is thumbs up with “nested using blocks (but ONLY if theare are pure nestings without any other code following the inner block.”

So, considering the source, I’m confident that I’m doing good by doing well (or however that goes) with nested using blocks (with out extra code after the inner block). 🙂

Using fs as New FilesStream(myfilepath,FileMode.Open)
  Using sr as new streamReader(fs)
     Try

       … still need exception handling around the other code

     catch ….
    Finally
    End Try
  End Using
End Using

Don’t Forget: www.acehaid.org

  Sign up for my newsletter so you don't miss my conference & Pluralsight course announcements!  

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.