Why is this an issue?
Disposing an object twice, either with the using
keyword or by calling Dispose
directly, in the same method is at best
confusing and at worst error-prone. The next developer might see only one of the Dispose
/using
and try to use an
already-disposed object.
In addition, even if the documentation of
Disposable
explicitly states that calling the Dispose
method multiple times should not throw an exception, some
implementation still do it. Thus it is safer to not dispose an object twice when possible.
This rule raises an issue when, in the same method, the Dispose
method is explicitly called twice on the same object, or when
using
is used with a direct call to Dispose()
.
Noncompliant code example
using (var d = new Disposable()) // Noncompliant
{
d.Dispose();
}
using var d = new Disposable();
d.Dispose(); // Noncompliant {{Refactor this code to make sure 'd' is disposed only once.}}
Compliant solution
using var d = new Disposable();