A type that implements System.IDisposable, and has fields that suggest the use of unmanaged resources, does not implement a finalizer as described by System.Object.Finalize.
Rule descriptionA violation of this rule is reported if the disposable type contains fields of the following types:
How to fix violationsTo fix a violation of this rule, implement a finalizer that calls your Dispose method.
When to suppress warningsIt is safe to suppress a warning from this rule if the type does not implement IDisposable for the purpose of releasing unmanaged resources.
Suppress a warningIf you just want to suppress a single violation, add preprocessor directives to your source file to disable and then re-enable the rule.
#pragma warning disable CA2216
// The code that's violating the rule is on this line.
#pragma warning restore CA2216
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA2216.severity = none
For more information, see How to suppress code analysis warnings.
ExampleThe following example shows a type that violates this rule.
public class DisposeMissingFinalize : IDisposable
{
private bool disposed = false;
private IntPtr unmanagedResource;
[DllImport("native.dll")]
private static extern IntPtr AllocateUnmanagedResource();
[DllImport("native.dll")]
private static extern void FreeUnmanagedResource(IntPtr p);
DisposeMissingFinalize()
{
unmanagedResource = AllocateUnmanagedResource();
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
// Dispose of resources held by this instance.
FreeUnmanagedResource(unmanagedResource);
disposed = true;
// Suppress finalization of this disposed instance.
if (disposing)
{
GC.SuppressFinalize(this);
}
}
}
public void Dispose()
{
Dispose(true);
}
// Disposable types with unmanaged resources implement a finalizer.
// Uncomment the following code to satisfy rule:
// DisposableTypesShouldDeclareFinalizer
// ~TypeA()
// {
// Dispose(false);
// }
}
CA1816: Call GC.SuppressFinalize correctly
See alsoRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4