‘Using’ statement added to VB in Whidbey release…

Scott Watermasysk blogs about the new 'Using' statement in VB.NET 2005...

Using in VB.NET
I have not touched VB.NET since early in .NET Beta 1, so I am a bit rusty. One thing I was happy to find is support for using statements in VB.NET 2005. It took me a try or two to figure out the syntax, so I figured I would post it here for future reference.

Public Class Class1

    Public Sub Go()
        Using sw As StreamWriter = New StreamWriter("C:\hey.txt")
        End Using
    End Sub

End Class

via MSDN: "The using statement obtains one or more resources, executes a statement, and then disposes of the resource."

For those unfamailar with a using statement, you can use for classes which implement IDisposable. As soon as the variable defined in the using section goes out of scope, Dispose is called.

In VB.NET 2003 or 2002, you can get the same effect with this style of code
        Dim sw as New StreamWriter("C:\hey.txt")
End Try

Comments (6)

  1. Tom says:

    I think most of us are numb to Whidbey. We are just trying to make a living when what we can use today.

    This tip included a sample for VB.NET 2003 … Thanks ! We would like to see more.


  2. Thanks for that Duncan… I’ve been playing with the Whidbey bits myself but mostly focussing (sp?) on the new controls and Generics.


    Like you I struggle with the current stuff which is why I’ve chosen to get a head start on the learning curve of Whidbey – it’s not really that far away now you know! 🙂

  3. "Applying Whidbey concepts in Everette" posts are great. Posts like that help us all prepare for Whidbey more than anything.

    Features are cool, mindset is key.

  4. Uhm, AFAIK, you can also get the same functionality by dropping the Try, Finally, and End Try keywords…

  5. Richard… that is only true if the code inside the Try is successful.

    If it throws an exception, your Dispose would never be called if I removed the Try, Finally and End Try keywords.

    That is the complete point of the Using construct in both C# (2002-2005) and VB 2005

Skip to main content