Search code examples
.netvb.netscopedispose

VB.NET 'someObj' is not disposed along all exception paths - I don't want to dispose it. Is my approach wrong?


VB.NET 2010, .NET 4

Hello,

I tried running code analysis the first time and found what it appears many others on SO doing the same have found: an abundance of

In method 'SomeMethod()', object 'SomeObject' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'SomeObject' before all references to it are out of scope.

warnings (CA2000). I've read a bunch of other threads on this here on SO, most of which had to do with the object in question possibly throwing an exception outside of a try block etc.

But what about something like this?

Private SomeContainer As New Panel
Private Sub SomePopulatorMethod()
  '..stuff..'
  For i As Integer = 0 To 9
    Dim newLabel as New Label
    newLabel.Text = i.ToString
    SomeContainer.Controls.Add(newLabel)
  Next
  '..other stuff..'
End Sub

In that case, I don't want newLabel to be disposed since it should remain in the panel. I do things like this when dynamically setting up a helper form where I create a bunch of textbox/label pairs to represent some data set. Is this approach fundamentally wrong? If so, how else should I go about it? I'm actually (sort of) alright with just letting sleeping dogs lie, but warnings make me sad... I'd like to do things right if only I could know how.

Any insight would be appreciated!
Thanks in advance,
Brian


Solution

  • Are you sure you're not getting bit by the problem mentioned in the final paragraph of the MSDN article you linked to?

    I can't say that your approach is incorrect, on the contrary. Generally speaking you shouldn't even have to worry about whether or not an object is disposable unless it somehow dictates that it needs to be used in a very specific way (as in with a using(x) { ... } block in C#). A stream for example implements IDisposable and can be used that way, or you can just call Close(), which is ultimately what it does when it's disposed.

    Most Forms controls are components which by definition implement IDisposable... it would be pretty tiring if you had to keep track of all of them with try/catch blocks. If that warning is showing up because the VB compiler is inserting arithmetic overflow checks on everything then just turn off the checks or ignore the warning.