Use ArgumentOutOfRangeException throw helper
Use ArgumentOutOfRangeException throw helper
Microsoft docsDescription
Argument 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.ArgumentOutOfRangeException.ThrowIfGreaterThan are simpler and more efficient than if blocks that construct a new exception instance.
Cause
Code checks whether an argument is less than or greater than a given value and then conditionally throws an System.ArgumentOutOfRangeException.
How to fix violations
Replace the if block that throws the exception with a call to one of the following throw-helper methods:
- System.ArgumentOutOfRangeException.ThrowIfZero`
1(`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfNegative`
1(`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfNegativeOrZero`
1(`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfLessThanOrEqual`
1(0,`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfLessThan`
1(0,`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual`
1(0,`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfGreaterThan`
1(0,`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfEqual`
1(0,`0,System.String) - System.ArgumentOutOfRangeException.ThrowIfNotEqual`
1(0,`0,System.String)
Or, in Visual Studio, use the lightbulb menu to fix your code automatically.
Example
void M(int arg)
{
if (arg is 0)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg < 0)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg <= 0)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg <= 42)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg < 42)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg > 42)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg >= 42)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg == 42)
throw new ArgumentOutOfRangeException(nameof(arg));
if (arg != 42)
throw new ArgumentOutOfRangeException(nameof(arg));
}
void M(int arg)
{
ArgumentOutOfRangeException.ThrowIfZero(arg);
ArgumentOutOfRangeException.ThrowIfNegative(arg);
ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arg);
ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(arg, 42);
ArgumentOutOfRangeException.ThrowIfLessThan(arg, 42);
ArgumentOutOfRangeException.ThrowIfGreaterThan(arg, 42);
ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(arg, 42);
ArgumentOutOfRangeException.ThrowIfEqual(arg, 42);
ArgumentOutOfRangeException.ThrowIfNotEqual(arg, 42);
}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.