rspec/rules/S2953/csharp/rule.adoc

112 lines
2.5 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
``++Dispose++`` as a method name should be used exclusively to implement ``++IDisposable.Dispose++`` to prevent any confusion.
It may be tempting to create a ``++Dispose++`` method for other purposes, but doing so will result in confusion and likely lead to problems in production.
=== 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
----
public class GarbageDisposal
{
private int Dispose() // Noncompliant
{
// ...
}
}
----
=== 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
----
public class GarbageDisposal : IDisposable
{
public void Dispose()
{
// ...
}
}
----
or
2022-02-04 17:28:24 +01:00
[source,csharp]
2021-04-28 16:49:39 +02:00
----
public class GarbageDisposal
{
private int Grind()
{
// ...
}
}
----
=== Exceptions
2021-04-28 16:49:39 +02:00
Methods named ``++Dispose++`` and invoked from the ``++IDisposable.Dispose++`` implementation are not reported.
[source,csharp]
2021-04-28 16:49:39 +02:00
----
public class GarbageDisposal : IDisposable
{
protected virtual void Dispose(bool disposing)
{
//...
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Either implement "IDisposable.Dispose", or rename this method to prevent confusion.
'''
== Comments And Links
(visible only on this page)
=== relates to: S1201
=== on 22 May 2015, 09:54:56 Tamas Vajk wrote:
LGTM
=== on 9 Jun 2015, 09:05:39 Tamas Vajk wrote:
\[~ann.campbell.2] I've changed all occurrences of "override" to "implement". I think it is better this way.
=== on 9 Jun 2015, 13:46:11 Ann Campbell wrote:
okay, thanks [~tamas.vajk]
=== on 18 Jun 2015, 11:41:33 Tamas Vajk wrote:
\[~ann.campbell.2] I've added an exception. This is a usual pattern in C#. You can read about it here: \https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx
=== on 18 Jun 2015, 12:00:49 Ann Campbell wrote:
okay [~tamas.vajk]
=== on 4 Aug 2015, 18:14:10 Ann Campbell wrote:
\[~tamas.vajk] I've just mapped this to FxCop's ImplementIDisposableCorrectly, but I believe that rule is broader than this one.
=== on 5 Aug 2015, 13:23:50 Tamas Vajk wrote:
\[~ann.campbell.2] Yes, it seems to me too that it is doing more. I'm not sure if we would want to add more disposable rules, or cover all the cases of this FxCop rule in this RSPEC.
=== on 20 Nov 2019, 10:31:27 Costin Zaharia wrote:
We should add an exception in this rule for https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#disposable-ref-structs[disposable ref structs] introduced in C# 8.
endif::env-github,rspecator-view[]