43 lines
1.3 KiB
Plaintext
43 lines
1.3 KiB
Plaintext
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 https://docs.microsoft.com/en-us/dotnet/api/system.idisposable.dispose?view=netcore-3.1[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();
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|