Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

ArgumentOutOfRangeException — argument outside the allowed range

System.ArgumentOutOfRangeException signals that an argument value is outside the set accepted by a method. The exception can identify the parameter name and the rejected value.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

throw new ArgumentOutOfRangeException(nameof(parameter), parameter, "Allowed range description.");

System.ArgumentOutOfRangeException derives from ArgumentException. Throw it when an argument has a value outside the range defined by the method, such as a percentage greater than 100. The range comes from the method's contract, not merely the limits of the numeric type.

The ArgumentOutOfRangeException(string, object, string) constructor takes the parameter name, rejected value, and message, in that order. Use nameof(percentage) to identify the parameter. The ParamName property exposes its name, while ActualValue exposes the value if one was supplied to the exception. Do not assume every such exception contains an ActualValue.

Usually, fix the call or validate input rather than using exceptions for ordinary control flow. In the example, catch is for demonstration only. The code prints selected properties instead of the full Message, keeping the expected output independent of the runtime's message language.

Examples

using System;

internal static class Program
{
    private static int ValidatePercentage(int percentage)
    {
        if (percentage < 0 || percentage > 100)
        {
            throw new ArgumentOutOfRangeException(
                nameof(percentage), percentage, "Expected 0 through 100.");
        }

        return percentage;
    }

    private static void Main()
    {
        Console.WriteLine(ValidatePercentage(50));

        try
        {
            ValidatePercentage(101);
        }
        catch (ArgumentOutOfRangeException ex)
        {
            Console.WriteLine($"{ex.ParamName}: {ex.ActualValue}");
        }
    }
}

Result

50
percentage: 101

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources