Using and Dispose

  • Thread starter Thread starter sam
  • Start date Start date
S

sam

Hi,
If I use "Using" do I sill need to call Dispose Method?
ex
Using F as Font=new Font(...)
.....
end Using
is that enough to free F
or, do I need to call F.dispose()
TIA
Sam
 
Hi,
If I use "Using" do I sill need to call Dispose Method?
ex
Using F as Font=new Font(...)
....
end Using
is that enough to free F
or, do I need to call F.dispose()
TIA
Sam

Using will call dispose for you - that is the whole reason for it :) It is
basically syntactical sugar for:

Dim o As SomeDisposableObject
Try
o = New DisposableObject()
o.DoCoolStuff()
Finally
If o IsNot Nothing Then
o.Dispose()
End If
End Try
 
Tom Shelton said:
Using will call dispose for you - that is the whole reason for it :) It
is
basically syntactical sugar for:

Dim o As SomeDisposableObject
Try
o = New DisposableObject()
o.DoCoolStuff()
Finally
If o IsNot Nothing Then
o.Dispose()
End If
End Try

I see it more like Sweet n Low instead of pure sugar :P


Mythran
 
sam said:
Hi,
If I use "Using" do I sill need to call Dispose Method?
ex
Using F as Font=new Font(...)
....
end Using
is that enough to free F
or, do I need to call F.dispose()
TIA
Sam

Pardon me if this is a bit patronising.

Following the advice provided by Tom (an excellent fellow), it is useful to
call many objects using the "Using" keyword. A further example is to call a
modal form this way e.g

Using frm As New frmMyForm()
frm.ShowDialog(Me)
End Using

or

Using frm As New frmMyForm()
With frm
.ShowDialog(Me)
If .DataChanged Then 'a user property of the form
Call RefreshRoutine 'some method to refresh data
End If
End With
End Using

I believe the "Using" statement guarantees disposal even if an error has
occurred
 
Hi,
If I use "Using" do I sill need to call Dispose Method?
ex
   Using F as Font=new Font(...)
....
   end Using
is that enough to free F
or, do I need to call F.dispose()
TIA
Sam

Like Tom said 'Using' does that for you. And by the way, 'Using' is
not the only construct that does that. The For Each loop will
automatically call Dispose on the IEnumerator if it happens to implent
IDisposable as well.
 
Like Tom said 'Using' does that for you. And by the way, 'Using' is
not the only construct that does that. The For Each loop will
automatically call Dispose on the IEnumerator if it happens to implent
IDisposable as well.

Thank goodness it does! What a pain that would be if it didn't - you would
have to write your for eaches that used disposable enumerators like:

Dim e As IEnumerator = o.GetEnumerator()
for each item as otype in e
...
next
e.dispose()

:)
 
Thank goodness it does!  What a pain that would be if it didn't - you would
have to write your for eaches that used disposable enumerators like:

Dim e As IEnumerator = o.GetEnumerator()
for each item as otype in e
        ...
next
e.dispose()

:)

Yeah, that would suck :)
 
Back
Top