Skip to content

Files

Latest commit

 

History

History
36 lines (27 loc) · 1.09 KB

File metadata and controls

36 lines (27 loc) · 1.09 KB

Pattern: Missing use of ArgumentOutOfRangeException

Issue: -

Description

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 ArgumentOutOfRangeException.ThrowIfGreaterThan are simpler and more efficient than if blocks that construct a new exception instance.

Example of incorrect code:

void TestMethod(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));
}

Example of correct code:

void TestMethod(int arg)
{
    ArgumentOutOfRangeException.ThrowIfZero(arg);
    ArgumentOutOfRangeException.ThrowIfNegative(arg);
    ArgumentOutOfRangeException.ThrowIfNegativeOrZero(arg);
}

Further Reading