2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
It is possible in an ``++IDisposable++`` to call ``++Dispose++`` on class members from any method, but the contract of ``++Dispose++`` is that it will clean up all unmanaged resources. Move disposing of members to some other method, and you risk resource leaks.
This rule also applies for disposable ref structs.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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 ResourceHolder : IDisposable
{
private FileStream fs;
public void OpenResource(string path)
{
this.fs = new FileStream(path, FileMode.Open);
}
public void CloseResource()
{
this.fs.Close();
}
public void CleanUp()
{
this.fs.Dispose(); // Noncompliant; Dispose not called in class' Dispose method
}
public void Dispose()
{
// method added to satisfy demands of interface
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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 ResourceHolder : IDisposable
{
private FileStream fs;
public void OpenResource(string path)
{
this.fs = new FileStream(path, FileMode.Open);
}
public void CloseResource()
{
this.fs.Close();
}
public void Dispose()
{
this.fs.Dispose();
}
}
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/459[CWE-459 - Incomplete Cleanup]
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
Move this "Dispose" call into this class' own "Dispose" method.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== relates to: S2930
=== on 22 May 2015, 09:52:57 Tamas Vajk wrote:
Removed the "noncompliant" comment from the compliant solution. Otherwise it looks good
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]