rspec/rules/S4002/csharp/rule.adoc

109 lines
1.9 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
This rule raises an issue when a disposable type contains fields of the following types and does not implement a finalizer:
* ``++System.IntPtr++``
* ``++System.UIntPtr++``
* ``++System.Runtime.InteropService.HandleRef++``
=== 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 System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
public class Foo : IDisposable // Noncompliant: Doesn't have a finalizer
{
private IntPtr myResource;
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
// Dispose of resources held by this instance.
FreeResource(myResource);
disposed = true;
// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}
public void Dispose() {
Dispose(true);
}
}
}
----
=== 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 System;
using System.Runtime.InteropServices;
namespace MyLibrary
{
public class Foo : IDisposable
{
private IntPtr myResource;
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
// Dispose of resources held by this instance.
FreeResource(myResource);
disposed = true;
// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}
~Foo()
{
Dispose(false);
}
}
}
----
== Resources
2021-04-28 16:49:39 +02:00
* Related: S3881 - "IDisposable" should be implemented correctly
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]