Code checks if an object is disposed and then conditionally throws an ObjectDisposedException.
Rule descriptionObject checks have a substantial impact on code size and often dominate the code for small functions and property setters. These checks prevent inlining and cause substantial instruction-cache pollution. Throw-helper methods such as ThrowIf are simpler and more efficient than if
blocks that construct a new exception instance.
The following code snippet shows a violation of CA1513:
class C
{
private bool _disposed = false;
void M()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
}
The following code snippet shows the fix:
class C
{
private bool _disposed = false;
void M()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
}
How to fix violations
Replace the if
block that throws the exception with a call to ThrowIf. Or, in Visual Studio, use the lightbulb menu to fix your code automatically.
It's safe to suppress a violation of this rule if you're not concerned about the maintainability of your code. It is also fine to suppress violations that are identified to be false positives.
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 CA1513
// The code that's violating the rule is on this line.
#pragma warning restore CA1513
To disable the rule for a file, folder, or project, set its severity to none
in the configuration file.
[*.{cs,vb}]
dotnet_diagnostic.CA1513.severity = none
For more information, see How to suppress code analysis warnings.
RetroSearch 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