Introduction To XML CommentsThe .NET Random Object

Using the Using Statement

May 20th, 2007

Yes. You can always take more than nothing.The .NET Framework 2.0 added the Using statement to VB.NET. Its purpose is to insure that objects using unmanaged resources, like file streams, database connections, and graphics, release their hold on resources as soon as possible. Using Using can simplify your code while insuring that critical resources are available for other processes as soon as possible.

Unmanaged objects in .NET always implement the IDisposable interface and provide a Dispose() method that you can call to release their resources immediately. However, it was common in earlier versions of VB.NET for programmers to forget to include the extra call to Dispose after using Close. This even creeped into some large code libraries that Microsoft and others released.

Now, in VS 2005, we can use a Using statement block to make our code cleaner looking and to avoid having unreleased objects causing errors.

Using is a block style structure. In the first line, you declare the object you want to work with, most often by declaring it with a New keyword, like so:

Using CurrentFile As New System.IO.StreamWriter("c:\docs\MyTextFile.txt")

After this would come your code that interacted with the disposible object. Finally, you end the block with End Using.

When execution leaves the block, the Dispose method of the object is called automatically, release the file or whatever object is associated with the block. Fortunately, .NET insures that the Dispose method is called no matter what. It even calls it if there is an unhandled exception (except for a StackOverflowException).

The Using block statement is a good way to enhance the stability of your application or component as well as making it easier to code and debug.

Share This Article: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Reddit
  • StumbleUpon
  • Technorati
  • DotNetKicks
  • DZone

Entry Filed under: VB.NET Tutorials


Rate This Article:

Not That GoodCould Be BetterOKGoodGreat (No Ratings Yet)
Loading ... Loading ...

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Most Popular Articles

Highest Rated Articles

Categories

Most Recent Articles

Feeds

 Subscribe in a reader

To subscribe by e-mail
Enter your address here

Delivered by FeedBurner

VB Opportunities

Archives