views:

61

answers:

1

From code analysis (Visual studio), I got this warning:

Warning 2 CA2000 : Microsoft.Reliability : ... Call System.IDisposable.Dispose on object 'l' before all references to it are out of scope...

So, I changed the code :

Dim l As LiteralControl = New LiteralControl
AddHandler l.DataBinding, AddressOf OnDataBinding
container.Controls.Add(l)

to

Dim l As LiteralControl = Nothing
Try
    l = New LiteralControl
    AddHandler l.DataBinding, AddressOf OnDataBinding
    container.Controls.Add(l)
Finally
    If Not l Is Nothing Then
        l.Dispose()
    End If
End Try

The warning disappear but then the literal control isn't anymore being displayed on the page...

EDIT

Note that the code come from a Microsoft web page : http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.instantiatein.aspx

+2  A: 

the warning is really about how the item could be created and then never actually hooked up to the container. hypothetically (but not realisticly), the AddHandler call could fail, and then the control would never be added to the container, and then nobody would ever dispose it.

instead of disposing on the finally (which is destroying your object all the time) you need to change that to a catch, and dispose in the catch, then rethrow the exception.

That will get rid of the warning and give you correct handling of dispose. Yes, in this specific case it isn't realistic, but it is possible.

John Gardner
Alternately, you could keep the `finally`, but null out the variable at the end of the `try`. Same difference, though, and your suggestion is probably clearer. I'm just offering this as something closer to the original.
Steven Sudit