Topic | Value |
---|---|
Id | IDISP003 |
Severity | Warning |
Enabled | True |
Category | IDisposableAnalyzers.Correctness |
Code | ArgumentAnalyzer |
AssignmentAnalyzer |
Dispose previous before re-assigning.
In the following example the old file will not be disposed when setting it to a new file in the Update
method.
public sealed class Foo : IDisposable
{
private FileStream stream = File.OpenRead("file.txt");
public void Update(string fileName)
{
this.stream = File.OpenRead(fileName);
}
public void Dispose()
{
this.stream.Dispose();
}
}
Dispose the old value before assigning a new value.
public sealed class Foo : IDisposable
{
private FileStream stream = File.OpenRead("file.txt");
public void Update(string fileName)
{
this.stream?.Dispose();
this.stream = File.OpenRead(fileName);
}
public void Dispose()
{
this.stream.Dispose();
}
}
Configure the severity per project, for more info see MSDN.
#pragma warning disable IDISP003 // Dispose previous before re-assigning
Code violating the rule here
#pragma warning restore IDISP003 // Dispose previous before re-assigning
Or put this at the top of the file to disable all instances.
#pragma warning disable IDISP003 // Dispose previous before re-assigning
[System.Diagnostics.CodeAnalysis.SuppressMessage("IDisposableAnalyzers.Correctness",
"IDISP003:Dispose previous before re-assigning",
Justification = "Reason...")]