2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-08-21 11:22:22 +02:00
An `IDisposable` object should be disposed (there are some rare exceptions where not disposing is fine, most notably `Task`). If a class has an `IDisposable` field, there can be two situations:
2021-01-06 17:38:34 +01:00
* The class observes a field that is under the responsibility of another class.
2023-08-21 11:22:22 +02:00
* The class owns the field, and is therefore responsible for calling `Dispose` on it.
2020-06-30 12:48:07 +02:00
2023-08-21 11:22:22 +02:00
In the second case, the safest way for the class to ensure `Dispose` is called is to call it in its own `Dispose` function, and therefore to be itself `IDisposable`. A class is considered to own an `IDisposable` field resource if it created the object referenced by the field.
2020-06-30 12:48:07 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:07 +02:00
2023-08-21 11:22:22 +02:00
[source,csharp,diff-id=1,diff-type=noncompliant]
2020-06-30 12:48:07 +02:00
----
public class ResourceHolder // Noncompliant; doesn't implement IDisposable
{
2023-08-21 11:22:22 +02:00
private FileStream fs; // This member is never Disposed
public void OpenResource(string path)
{
this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it
}
public void CloseResource()
{
this.fs.Close();
}
2020-06-30 12:48:07 +02:00
}
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:07 +02:00
2023-08-21 11:22:22 +02:00
[source,csharp,diff-id=1,diff-type=compliant]
2020-06-30 12:48:07 +02:00
----
public class ResourceHolder : IDisposable
2023-08-21 11:22:22 +02:00
{
private FileStream fs;
public void OpenResource(string path)
{
this.fs = new FileStream(path, FileMode.Open); // I create the FileStream, I'm owning it
}
public void CloseResource()
{
this.fs.Close();
}
public void Dispose()
{
this.fs.Dispose();
}
2020-06-30 12:48:07 +02:00
}
----
2023-05-03 11:06:20 +02:00
== Resources
2020-06-30 12:48:07 +02:00
2024-01-15 17:15:56 +01:00
* CWE - https://cwe.mitre.org/data/definitions/459[CWE-459 - Incomplete Cleanup]