S3966 — Objects should not be disposed more than once

Language
VB.NET
Type
Code smell
Severity
Major
Tags
confusing, pitfall, symbolic-execution

Why is this an issue?

Disposing an object twice in the same method, either with the Using statement or by calling Dispose directly, is confusing and error-prone. For example, another developer might try to use an already-disposed object, or there can be runtime errors for specific paths in the code.

In addition, even if the documentation explicitly states that calling the Dispose method multiple times should not throw an exception, some implementations still do it. Thus it is safer to not dispose of an object twice when possible.

How to fix it

Code examples

Noncompliant code example


Dim foo As New Disposable()
foo.Dispose()
foo.Dispose() ' Noncompliant

Using bar As New Disposable()  ' Noncompliant
    bar.Dispose()
End Using

Compliant solution


Dim foo As New Disposable()
foo.Dispose()

Using bar As New Disposable()  ' Compliant

End Using

Resources

Documentation

↑ Back to top