Table of Contents

ArrayExtensions Class

Definition

Namespace
Bodu.Extensions
Assembly
Bodu.Core.dll
Package
Bodu.Core 1.0.1
Source
ArrayExtensions.Clear.cs

Provides allocation-aware operations over Array instances - clearing, copying, slicing, and reversing - that either match the missing primitives on Array or supply more ergonomic counterparts to the BCL helpers.

public static class ArrayExtensions
Inheritance
ArrayExtensions
Inherited Members

Remarks

The Array type ships with a useful but uneven surface: Reverse(Array) mutates in place while LINQ's Reverse allocates a new sequence; Clear(Array, int, int) requires explicit bounds; and there is no Slice for plain arrays at all. This class fills those gaps with overload sets that work both on the strongly typed T[] form and the non-generic Array base, so callers can choose the version that matches the data they already hold.

The API surface is grouped around four operations: bulk-reset (Clear), shallow duplication (Copy), windowed views returned as freshly allocated arrays (Slice), and whole-array or windowed element reversal ( Reverse). Each operation accepts a default whole-array form together with an indexed-range and Range-based overload, giving the same shape of API regardless of how the caller prefers to express the window.

All methods validate their inputs through ThrowHelper and reject null arrays with ArgumentNullException. Reverse, Slice, and Copy always allocate: each returns a new array and leaves the source untouched - Reverse copies the full source and reverses the nominated window on the copy, unlike the in-place Reverse(Array). Only Clear mutates the source array. Operations are not thread-safe - callers are responsible for synchronizing access to a shared array.

int[] source = { 1, 2, 3, 4, 5, 6 };

// Reverse only the middle window - returns a new array; source is unchanged.
int[] reversed = source.Reverse(1, 4); // => { 1, 5, 4, 3, 2, 6 }

// Take a freshly allocated slice using a Range expression.
int[] tail = source.Slice(2..); // => { 3, 4, 5, 6 }

// Clear the prefix in place without touching the tail.
source.Clear(0, 3); // => source is now { 0, 0, 0, 4, 5, 6 }

Methods

Clear(Array)

Sets all elements in an Array to the default value of each element type.

public static void Clear(this Array array)

Parameters

array Array

The array whose elements to clear.

Remarks

This method supports only single-dimensional, zero-based arrays.

Exceptions

ArgumentNullException

array is null.

ArgumentException

array is not a single-dimensional array.
-or-
array does not have a zero-based index.

Clear(Array, int)

Sets all elements in an Array to the default value of each element type, starting from the specified index to the end of the array.

public static void Clear(this Array array, int index)

Parameters

array Array

The array whose elements to clear.

index int

The zero-based index at which to begin clearing elements.

Remarks

Clears elements from index to the end of the array.

Exceptions

ArgumentNullException

array is null.

ArgumentException

array is not a single-dimensional array.
-or-
array does not have a zero-based index.

ArgumentOutOfRangeException

index is less than 0 or greater than the length of array.

Clear(Array, int, int)

Sets a specified number of elements in an Array to the default value of each element type, starting from a given index.

public static void Clear(this Array array, int index, int count)

Parameters

array Array

The array whose elements to clear.

index int

The zero-based index at which to begin clearing elements.

count int

The number of elements to clear.

Remarks

Clears count elements starting at index.

Exceptions

ArgumentNullException

array is null.

ArgumentException

array is not a single-dimensional array.
-or-
array does not have a zero-based index.

ArgumentOutOfRangeException

index is less than 0 or greater than the length of array.
-or-
count is less than 0 or extends beyond the end of the array.

Clear<T>(T[])

Sets all elements in a one-dimensional array to the default value of the element type.

public static void Clear<T>(this T[] array)

Parameters

array T[]

The one-dimensional array to clear.

Type Parameters

T

The type of the elements of the array.

Exceptions

ArgumentNullException

array is null.

Clear<T>(T[], int)

Sets all elements in a one-dimensional array to the default value of the element type, starting from the specified index to the end of the array.

public static void Clear<T>(this T[] array, int index)

Parameters

array T[]

The one-dimensional array to clear.

index int

The zero-based index at which to begin clearing elements.

Type Parameters

T

The type of the elements of the array.

Remarks

This method clears elements starting from index to the end of the array. The number of elements cleared is array.Length - index.

Exceptions

ArgumentNullException

array is null.

ArgumentOutOfRangeException

index is less than 0 or greater than the length of array.

Clear<T>(T[], int, int)

Sets a specified number of elements in a one-dimensional array to the default value of the element type, starting from a given index.

public static void Clear<T>(this T[] array, int index, int count)

Parameters

array T[]

The one-dimensional array to clear.

index int

The zero-based index at which to begin clearing elements.

count int

The number of elements to clear.

Type Parameters

T

The type of the elements of the array.

Remarks

This method clears exactly count elements starting at index.

Exceptions

ArgumentNullException

array is null.

ArgumentOutOfRangeException

index is less than 0 or greater than the length of array.
-or-
count is less than 0 or extends beyond the end of the array.

Copy<T>(T[])

Creates a shallow copy of the specified array of value types. Returns null if the source array is null.

public static T[] Copy<T>(this T[] array) where T : struct

Parameters

array T[]

The array to copy.

Returns

T[]

A new array containing the same elements as the source, or null if the source is null.

Type Parameters

T

The value type of the elements in the array.

PadLeft<T>(T[], int, T)

Returns a new array of length totalLength whose trailing elements are the contents of array and whose leading positions are filled with padValue.

public static T[] PadLeft<T>(this T[] array, int totalLength, T padValue)

Parameters

array T[]

The source array to right-align in the result.

totalLength int

The desired length of the result.

padValue T

The value used to fill the leading positions.

Returns

T[]

A new array of length totalLength. When totalLength equals array.Length the result is a fresh copy of array with no padding.

Type Parameters

T

The element type of the array.

Exceptions

ArgumentNullException

array is null.

ArgumentOutOfRangeException

totalLength is less than array.Length.

PadRight<T>(T[], int, T)

Returns a new array of length totalLength whose leading elements are the contents of array and whose trailing positions are filled with padValue.

public static T[] PadRight<T>(this T[] array, int totalLength, T padValue)

Parameters

array T[]

The source array to left-align in the result.

totalLength int

The desired length of the result.

padValue T

The value used to fill the trailing positions.

Returns

T[]

A new array of length totalLength. When totalLength equals array.Length the result is a fresh copy of array with no padding.

Type Parameters

T

The element type of the array.

Exceptions

ArgumentNullException

array is null.

ArgumentOutOfRangeException

totalLength is less than array.Length.

Slice<T>(T[], int)

Takes a slice of the specified array starting from a given index and extending to the end of the array.

public static T[] Slice<T>(this T[] array, int index)

Parameters

array T[]

The source array containing the elements to slice.

index int

The starting index in the source array from which the slice begins.

Returns

T[]

A new array containing elements from the array starting from index to the end.

Type Parameters

T

The type of the elements in the array.

Exceptions

ArgumentNullException

Thrown when array is null.

ArgumentOutOfRangeException

Thrown when index is out of bounds.

Slice<T>(T[], int, int)

Takes a slice of the specified array starting from a given index and extending for a specified number of elements.

public static T[] Slice<T>(this T[] array, int index, int count)

Parameters

array T[]

The source array containing the elements to slice.

index int

The starting index in the source array from which the slice begins.

count int

The number of elements to include in the slice.

Returns

T[]

A new array containing the sliced elements from the array starting at index.

Type Parameters

T

The type of the elements in the array.

Exceptions

ArgumentNullException

Thrown when array is null.

ArgumentOutOfRangeException

Thrown when index or count is less than zero.

ArgumentException

Thrown when index and count describe an invalid range within array.

ToMatrix<T>(T[][], bool)

Copies the elements of a jagged array into a newly allocated two-dimensional array.

public static T[,] ToMatrix<T>(this T[][] source, bool transpose)

Parameters

source T[][]

The jagged source array. All inner arrays must be non-null and have the same length.

transpose bool

When false, the result has shape [rows, cols] matching source; when true, rows and columns are swapped to produce a shape of [cols, rows].

Returns

T[,]

A new rectangular array containing the values from source.

Type Parameters

T

The element type.

Exceptions

ArgumentNullException

source is null, or any inner array is null.

ArgumentException

source contains no rows, or the inner arrays do not all share the same length.

ToReversed(Array)

Creates a new single-dimensional array containing all elements of source in reverse order.

public static Array ToReversed(this Array source)

Parameters

source Array

The array whose elements will be reversed.

Returns

Array

A new Array of the same element type and length as source, with all elements in reverse order.

Remarks

Delegates to ToReversed(Array, int, int) with index = 0 and count = source.Length. See that overload for full implementation details. Prefer the generic ToReversed<T>(T[]) overload where the element type is known at compile time; the non-generic path cannot use Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32) and falls back to Copy(Array, Array, int) and Reverse(Array, int, int).

Exceptions

ArgumentNullException

Thrown when source is null.

ArgumentException

Thrown when source is not a single-dimensional array. Reverse(Array, int, int), which is used internally, does not support multidimensional arrays.

ToReversed(Array, int, int)

Creates a new single-dimensional array that is a copy of source with elements in the specified range reversed, leaving all other elements in their original positions.

public static Array ToReversed(this Array source, int index, int count)

Parameters

source Array

The array to copy and partially reverse.

index int

The zero-based index of the first element in the range to reverse. Must be non-negative and less than or equal to source.Length.

count int

The number of elements to reverse. Must be non-negative and, together with index, must not exceed source.Length. A value of zero or one results in a straight copy with no reversal performed.

Returns

Array

A new Array of the same element type and length as source, where elements in [index, index + count) appear in reverse order and all other elements are copied unchanged.

Remarks

This is the canonical non-generic implementation. The full-array overload (ToReversed(Array)) and the Range-based overload (ToReversed(Array, Range)) both resolve their arguments and delegate here.

Unlike the typed ToReversed<T>(T[], int, int) overload, this method cannot delegate to Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32) because the element type is not known at compile time. Instead it uses CreateInstance(Type, int) to allocate a correctly typed result, Copy(Array, Array, int) to populate it, and Reverse(Array, int, int) to reverse the nominated slice in-place on the copy. These BCL methods are used internally via Bodu.Extensions.ArrayExtensions.ReverseArrayCore(System.Array,System.Int32,System.Int32).

Bounds validation is delegated to ThrowIfArrayOffsetOrCountInvalid(Array, int, int, string?, string?, string?), which also guards against null. The rank check is performed separately because ThrowIfArrayOffsetOrCountInvalid(Array, int, int, string?, string?, string?) does not inspect Rank.

Exceptions

ArgumentNullException

Thrown when source is null.

ArgumentException

Thrown when source is not a single-dimensional array, or when index + count exceeds source.Length.

ArgumentOutOfRangeException

Thrown when index or count is negative or exceeds source.Length.

ToReversed(Array, Range)

Creates a new single-dimensional array that is a copy of source with elements in the specified Range reversed, leaving all other elements in their original positions.

public static Array ToReversed(this Array source, Range range)

Parameters

source Array

The array to copy and partially reverse.

range Range

The range of elements to reverse. Both start-relative (e.g. 1..4) and end-relative (e.g. ^4..^1) index expressions are supported. A range covering zero or one element results in a straight copy with no reversal performed.

Returns

Array

A new Array of the same element type and length as source, where elements within range appear in reverse order and all elements outside range are copied unchanged.

Remarks

Resolves range via GetOffsetAndLength(int) and delegates to Bodu.Extensions.ArrayExtensions.ReverseArrayCore(System.Array,System.Int32,System.Int32). Prefer ToReversed(Array, int, int) when the start and count are already available as integers to avoid constructing an intermediate Range value.

Exceptions

ArgumentNullException

Thrown when source is null.

ArgumentException

Thrown when source is not a single-dimensional array.

ArgumentOutOfRangeException

Thrown when range resolves to a start index that is negative or to an end index that exceeds source.Length. Resolution is performed by GetOffsetAndLength(int).

ToReversed<T>(T[])

Creates a new array containing all elements of source in reverse order.

public static T[] ToReversed<T>(this T[] source)

Parameters

source T[]

The array whose elements will be reversed.

Returns

T[]

A new T[] containing all elements of source in reverse order.

Type Parameters

T

The type of elements in the array.

Remarks

Converts source to a ReadOnlySpan<T> via AsSpan<T>(T[]) and delegates to Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32), which performs the SIMD-accelerated copy and reversal. See ToReversed<T>(T[], int, int) for full performance and allocation details.

Exceptions

ArgumentNullException

Thrown when source is null.

ToReversed<T>(T[], int, int)

Creates a new array that is a copy of source with elements in the specified range reversed, leaving all other elements in their original positions.

public static T[] ToReversed<T>(this T[] source, int index, int count)

Parameters

source T[]

The array to copy and partially reverse.

index int

The zero-based index of the first element in the range to reverse. Must be non-negative and less than or equal to source.Length.

count int

The number of elements to reverse. Must be non-negative and, together with index, must not exceed source.Length. A value of zero or one results in a straight copy with no reversal performed.

Returns

T[]

A new T[] of the same length as source, where elements in [ index, index + count) appear in reverse order and all other elements are copied unchanged.

Type Parameters

T

The type of elements in the array.

Examples

int[] data = { 1, 2, 3, 4, 5 };
int[] full = data.ToReversed(); // [ 5, 4, 3, 2, 1 ]
int[] partial = data.ToReversed(index: 1, count: 3); // [ 1, 4, 3, 2, 5 ]

Remarks

This is the canonical typed-array implementation. The full-array overload (ToReversed<T>(T[])) and the Range-based overload (ToReversed<T>(T[], Range)) both resolve their arguments and delegate here.

Bounds validation is delegated to ThrowIfSpanOffsetOrCountInvalid<T>(ReadOnlySpan<T>, int, int, string?, string?, string?) , which uses unsigned comparison to catch both negative values and out-of-bounds values in a single branch. Validated arguments are then forwarded to Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32), which performs the SIMD-accelerated copy and in-place reversal of the nominated slice.

Exceptions

ArgumentNullException

Thrown when source is null.

ArgumentOutOfRangeException

Thrown when index is negative or greater than source.Length, or when count is negative or would extend the range beyond the end of source.

ToReversed<T>(T[], Range)

Creates a new array that is a copy of source with elements in the specified Range reversed, leaving all other elements in their original positions.

public static T[] ToReversed<T>(this T[] source, Range range)

Parameters

source T[]

The array to copy and partially reverse.

range Range

The range of elements to reverse. Both start-relative (e.g. 1..4) and end-relative (e.g. ^4..^1) index expressions are supported. A range covering zero or one element results in a straight copy with no reversal performed.

Returns

T[]

A new T[] of the same length as source, where elements within range appear in reverse order and all elements outside range are copied unchanged.

Type Parameters

T

The type of elements in the array.

Examples

int[] data = { 1, 2, 3, 4, 5 };
int[] fromStart = data.ToReversed(1..4); // [ 1, 4, 3, 2, 5 ]
int[] fromEnd = data.ToReversed(^4..^1); // [ 1, 4, 3, 2, 5 ]

Remarks

Resolves range via GetOffsetAndLength(int) and delegates to Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32). Prefer ToReversed<T>(T[], int, int) when the start and count are already available as integers to avoid constructing an intermediate Range value.

Exceptions

ArgumentNullException

Thrown when source is null.

ArgumentOutOfRangeException

Thrown when range resolves to a start index that is negative or to an end index that exceeds source.Length. Resolution is performed by GetOffsetAndLength(int); the resulting values are forwarded directly to Bodu.Extensions.ArrayExtensions.ReverseCore``1(System.ReadOnlySpan{``0},System.Int32,System.Int32) without a second validation pass.

Applies to

ProductVersions
.NET8, 10