ErrLookup › Background articles › ArgumentOutOfRangeException: .NET throws it when an argument value is out of range, empty, or hits an unmapped switch case
ArgumentOutOfRangeException: .NET throws it when an argument value is out of range, empty, or hits an unmapped switch case
ArgumentOutOfRangeException is the .NET base-class-library exception a method throws when an argument's value falls outside its allowed range. Developers meet it most often as a synchronous throw at method entry naming the offending parameter via ParamName. Across the documented libraries it fires in three situations: a numeric value that went negative or oversized, a collection sized to zero where work was expected, or an enum/type value that fell through to a switch statement's default branch. The largest documented cluster is the zero-length case, where the type is sometimes used in place of the more idiomatic ArgumentException.
Distilled from 695 documented records across 43 repositories.
Background
ArgumentOutOfRangeException inherits from ArgumentException and is provided by the .NET base class library. A method throws it to fail fast when a scalar argument's value is outside the allowed range: a negative length, an index past the end, an enum member not in the defined set, or a size exceeding a fixed buffer. The thrower identifies the offending parameter through ParamName and may add a message and the actual value. It is a precondition mechanism: the method refuses to compute a meaningless or unsafe result rather than proceed and corrupt state.,The records show three shapes of this family, and the exception was designed for only the first. The numeric-range shape is the textbook one: Newtonsoft.Json's internal StringUtils.Trim rejects a negative length argument, and Orleans' EventHubQueueCache.GetSegment rejects a single Event Hub message whose serialized size exceeds the capacity of a pooled buffer block. In both cases a real value crossed a numeric bound, which is exactly what ArgumentOutOfRangeException exists to signal.,The second shape is the switch-default guard. A method dispatches over an enum or a runtime type and its default branch throws for any value the switch does not list. BenchmarkDotNet's toolchain resolver throws for a Runtime concrete type outside its six handled cases and again for a RuntimeMoniker enum value with no case; WPFUI's title-bar button maps each TitleBarButtonType to a Windows hit-test code and throws for any value that is not a defined member; Newtonsoft's BSON writer throws when it meets a BsonToken type it does not know how to serialize. These reads as an exhaustive switch that someone extended the enum or type hierarchy past. The throw is defensive, and in normal use it is often unreachable, but it surfaces whenever a newer enum member, a custom subclass, or a hand-built token reaches the switch.,The third and largest shape is the empty-collection guard, concentrated in StockSharp's GPU indicator calculators. Each calculator sizes a kernel grid and its output buffers from the lengths of the candlesSeries and parameters arrays, so a zero-length array collapses a grid axis or produces zero-sized buffers, and Calculate throws at method entry rather than launch a meaningless kernel. This shape is the family's quiet controversy. An empty array is a valid object with zero elements, so the idiomatic .NET choice for a must-not-be-empty collection is ArgumentException with a descriptive message, and several StockSharp records flag the misuse explicitly. The same codebase also has the identical guard without the flag, so the pattern is partly intentional: a single exception type for any failed precondition. Callers who need to catch these should catch ArgumentException, the shared base, to cover both the correct and the misused shapes.,From the caller's side every shape looks the same: a synchronous throw before any work is done, with ParamName naming the argument. The remedy therefore always lives at the call site or one layer upstream. Validate the value, map the enum, fill the collection, or set an explicit override so the dispatching method is never reached. The exception is library-internal contract enforcement, not a transient fault, so retrying the identical call will not help.
Common causes
- Empty array or collection passed where work is sized from it.The dominant cluster. A method computes a buffer length, a kernel grid extent, or an output shape from the input array's Length, and a zero-length input collapses that dimension to nothing. StockSharp's GPU indicator calculators (FVE, Gator, Fibonacci, FRAMA, Fractal Dimension, Forecast Oscillator, Fractals, Force Index, Envelope, GApO, Standard Error, RSI, RVAverage) all throw on candlesSeries.Length == 0 or parameters.Length == 0. The trigger is usually an upstream filter, query, or config sweep that yielded no entries and was forwarded without a count check.
- Unmapped enum value reaches a switch default.A switch dispatches over an enum and throws for any value it does not list. BenchmarkDotNet throws for a RuntimeMoniker with no toolchain case, and WPFUI throws for a TitleBarButtonType outside the known members. The usual entry path is an enum member added in a newer library version, a raw numeric cast into the enum, or a value bound from XAML or deserialization that is not in the defined set.
- Unhandled runtime type in a type-dispatch switch.A method switches on a runtime object's concrete type and throws for anything outside the handled set. BenchmarkDotNet's GetToolchain handles six Runtime subclasses and throws for a custom subclass or a type from a version-mismatched assembly. It is reached only when no explicit toolchain is set on the Job, forcing dispatch by runtime type.
- Computed or derived value goes negative or past a bound.A length or offset derived from a delimiter index, an arithmetic expression, or a subtraction underflows or overshoots. Newtonsoft's internal StringUtils.Trim throws when the length argument is negative. In application code the value usually comes from an unchecked calculation rather than a literal.
- Payload or message exceeds a fixed capacity.A sized buffer or block has a hard maximum, and a single payload larger than that maximum can never fit. Orleans' EventHubQueueCache.GetSegment throws when an Event Hub message's serialized size (offset plus partition key plus properties plus payload) exceeds the buffer block capacity. Large custom metadata in EventData properties can push an otherwise normal payload over the limit.
- Unsupported token or type handed to a serializer writer.A writer maps incoming tokens to a fixed set of output primitives and throws for anything outside that set. Newtonsoft's BsonBinaryWriter throws on a BsonToken type it cannot serialize to binary, which surfaces when a CLR type such as Guid is not wrapped as a supported primitive or when a hand-built BsonToken tree contains an exotic leaf.
What usually fixes it
- Guard the value at the call site before invoking the method: check array Length greater than zero, validate enum members with Enum.IsDefined, and confirm sizes fit before the call. The exception is a precondition, so the identical retry will fail again; the fix is to change the input.
- Validate at the trust boundary rather than only at the throwing method. Check config and parameter sweeps for empty results at load time, verify API and database responses returned rows at the data boundary, and short-circuit batch pipelines for symbols with insufficient data instead of forwarding empty arrays.
- For dispatch-by-type or dispatch-by-enum switches, avoid relying on automatic resolution. Set an explicit override so the dispatching method is never reached: BenchmarkDotNet's .WithToolchain(...) short-circuits runtime and moniker dispatch. Keep the library version aligned with the enum definitions you depend on so new members have matching cases.
- Throw the correct type when you are the author. Use ArgumentOutOfRangeException for a numeric or positional value outside its range, and use ArgumentException with a descriptive message for an empty collection. Several StockSharp records document ArgumentOutOfRangeException being used for an empty-array check where ArgumentException is idiomatic.
- Register converters or mappings for types the library does not natively handle. Newtonsoft BSON accepts a custom JsonConverter or BsonConverter to serialize CLR types like Guid as a supported primitive, preventing the unsupported-token throw.
- Catch ArgumentException, the shared base, when you must handle these at a boundary. It covers both the correctly typed numeric-range throw and the misused empty-collection throw, so a single catch stays correct if the library changes the concrete type in a later version.
Go deeper
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Documented occurrences
- length(JamesNK/Newtonsoft.Json)
- parameters(StockSharp/StockSharp)
- nameof(parameters)(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
- candlesSeries(StockSharp/StockSharp)
- parameters(StockSharp/StockSharp)
…and 675 more across the corpus — use search.
Honest provenance: generated on 2026-08-13 from AI-assisted analysis of the linked records. See how records are made.