rspec/rules/S3966/csharp/rule.adoc

48 lines
1.4 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
using (var d = new Disposable()) // Noncompliant
{
d.Dispose();
}
----
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
using var d = new Disposable();
d.Dispose(); // Noncompliant {{Refactor this code to make sure 'd' is disposed only once.}}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
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[]