28

I am coding in VB.NET.

Currently, I am enclosing object initialization and usage in a Try/Catch block and then tear it down (dispose, close, set to nothing) in the Finally block. The problem is, a C# 'using' block is so easy to use and would clean things up in my code.

Is there a VB.NET equivalent? Or is my Finally block tear-down solution the only way?

crackedcornjimmy
  • 1,972
  • 5
  • 26
  • 42

4 Answers4

48

It's the same, it's just:

Using conn As New SqlConnection
    ....
End Using
Hans Olsson
  • 54,199
  • 15
  • 94
  • 116
7

http://msdn.microsoft.com/en-us/library/htd05whh(VS.80).aspx

Public Sub setbigbold(ByVal c As Control)
    Using nf As New System.Drawing.Font("Arial", 12.0F, _
        System.Drawing.FontStyle.Bold)

        c.Font = nf
        c.Text = "This is 12-point Arial bold"
    End Using
End Sub
Alex
  • 34,899
  • 5
  • 77
  • 90
  • 6
    This definitely needs a better example. This is a guaranteed ObjectDisposedException. – Hans Passant Sep 02 '10 at 21:26
  • 1
    @crackedcornjimmy: Yes. The font is assigned to a property in the control, and then it's disposed. When the control tries to use the font, the actual GDI font is gone. – Guffa Sep 02 '10 at 21:32
  • 1
    @Guffa: So the Font property doesn't make a copy of the font and dispose of its old one? How is one supposed to keep track of who owns control fonts? – supercat Sep 02 '10 at 22:13
  • It should come as no surprise that the page cited above by @xandercoded has moved. The new address is https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/using-statement. – David A. Gray Jul 10 '19 at 18:45
6

Er, Using ... End Using

See MSDN for more info

Rowland Shaw
  • 37,700
  • 14
  • 97
  • 166
0

Here is another StackOverflow question that deals with the exact same issue. If I'm not mistaken it's used in a very similar, if not the exact same, way as in C# though.

Hope this helps!

Community
  • 1
  • 1
AmbiguousX
  • 1,704
  • 4
  • 24
  • 39