Use ObjectDisposedException throw helper
Use ObjectDisposedException throw helper
Microsoft docsDescription
Object 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 System.ObjectDisposedException.ThrowIf are simpler and more efficient than if blocks that construct a new exception instance.
Cause
Code checks if an object is disposed and then conditionally throws an System.ObjectDisposedException.
How to fix violations
Replace the if block that throws the exception with a call to System.ObjectDisposedException.ThrowIf. Or, in Visual Studio, use the lightbulb menu to fix your code automatically.
Example
class C
{
private bool _disposed = false;
void M()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
}
}
class C
{
private bool _disposed = false;
void M()
{
ObjectDisposedException.ThrowIf(_disposed, this);
}
}When to suppress
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.