rspec/rules/S2952/csharp/rule.adoc
2021-04-28 18:08:03 +02:00

62 lines
1.2 KiB
Plaintext

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.
== Noncompliant Code Example
----
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
}
}
----
== Compliant Solution
----
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();
}
}
----
== See
* http://cwe.mitre.org/data/definitions/459.html[MITRE, CWE-459] - Incomplete Cleanup