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
arrayArrayThe array whose elements to clear.
Remarks
This method supports only single-dimensional, zero-based arrays.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentException
arrayis not a single-dimensional array.
-or-arraydoes 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
arrayArrayThe array whose elements to clear.
indexintThe zero-based index at which to begin clearing elements.
Remarks
Clears elements from index to the end of the array.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentException
arrayis not a single-dimensional array.
-or-arraydoes not have a zero-based index.- ArgumentOutOfRangeException
indexis less than 0 or greater than the length ofarray.
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
arrayArrayThe array whose elements to clear.
indexintThe zero-based index at which to begin clearing elements.
countintThe number of elements to clear.
Remarks
Clears count elements starting at index.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentException
arrayis not a single-dimensional array.
-or-arraydoes not have a zero-based index.- ArgumentOutOfRangeException
indexis less than 0 or greater than the length ofarray.
-or-countis 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
arrayT[]The one-dimensional array to clear.
Type Parameters
TThe type of the elements of the array.
Exceptions
- ArgumentNullException
arrayis 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
arrayT[]The one-dimensional array to clear.
indexintThe zero-based index at which to begin clearing elements.
Type Parameters
TThe 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
arrayis null.- ArgumentOutOfRangeException
indexis less than 0 or greater than the length ofarray.
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
arrayT[]The one-dimensional array to clear.
indexintThe zero-based index at which to begin clearing elements.
countintThe number of elements to clear.
Type Parameters
TThe type of the elements of the array.
Remarks
This method clears exactly count elements starting at index.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
indexis less than 0 or greater than the length ofarray.
-or-countis 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
arrayT[]The array to copy.
Returns
Type Parameters
TThe 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
arrayT[]The source array to right-align in the result.
totalLengthintThe desired length of the result.
padValueTThe value used to fill the leading positions.
Returns
- T[]
A new array of length
totalLength. WhentotalLengthequalsarray.Lengththe result is a fresh copy ofarraywith no padding.
Type Parameters
TThe element type of the array.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
totalLengthis less thanarray.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
arrayT[]The source array to left-align in the result.
totalLengthintThe desired length of the result.
padValueTThe value used to fill the trailing positions.
Returns
- T[]
A new array of length
totalLength. WhentotalLengthequalsarray.Lengththe result is a fresh copy ofarraywith no padding.
Type Parameters
TThe element type of the array.
Exceptions
- ArgumentNullException
arrayis null.- ArgumentOutOfRangeException
totalLengthis less thanarray.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
arrayT[]The source array containing the elements to slice.
indexintThe starting index in the source array from which the slice begins.
Returns
- T[]
A new array containing elements from the
arraystarting fromindexto the end.
Type Parameters
TThe type of the elements in the array.
Exceptions
- ArgumentNullException
Thrown when
arrayis null.- ArgumentOutOfRangeException
Thrown when
indexis 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
arrayT[]The source array containing the elements to slice.
indexintThe starting index in the source array from which the slice begins.
countintThe number of elements to include in the slice.
Returns
- T[]
A new array containing the sliced elements from the
arraystarting atindex.
Type Parameters
TThe type of the elements in the array.
Exceptions
- ArgumentNullException
Thrown when
arrayis null.- ArgumentOutOfRangeException
Thrown when
indexorcountis less than zero.- ArgumentException
Thrown when
indexandcountdescribe an invalid range withinarray.
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
sourceT[][]The jagged source array. All inner arrays must be non-null and have the same length.
transposeboolWhen false, the result has shape
[rows, cols]matchingsource; 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
TThe element type.
Exceptions
- ArgumentNullException
- ArgumentException
sourcecontains 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
sourceArrayThe 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
sourceis null.- ArgumentException
Thrown when
sourceis 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
sourceArrayThe array to copy and partially reverse.
indexintThe zero-based index of the first element in the range to reverse. Must be non-negative and less than or equal to
source.Length.countintThe number of elements to reverse. Must be non-negative and, together with
index, must not exceedsource.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
sourceis null.- ArgumentException
Thrown when
sourceis not a single-dimensional array, or whenindex + countexceedssource.Length.- ArgumentOutOfRangeException
Thrown when
indexorcountis negative or exceedssource.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
sourceArrayThe array to copy and partially reverse.
rangeRangeThe 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 withinrangeappear in reverse order and all elements outsiderangeare 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
sourceis null.- ArgumentException
Thrown when
sourceis not a single-dimensional array.- ArgumentOutOfRangeException
Thrown when
rangeresolves to a start index that is negative or to an end index that exceedssource.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
sourceT[]The array whose elements will be reversed.
Returns
- T[]
A new
T[] containing all elements ofsourcein reverse order.
Type Parameters
TThe 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
sourceis 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
sourceT[]The array to copy and partially reverse.
indexintThe zero-based index of the first element in the range to reverse. Must be non-negative and less than or equal to
source.Length.countintThe number of elements to reverse. Must be non-negative and, together with
index, must not exceedsource.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 assource, where elements in [index,index+count) appear in reverse order and all other elements are copied unchanged.
Type Parameters
TThe 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
sourceis null.- ArgumentOutOfRangeException
Thrown when
indexis negative or greater thansource.Length, or whencountis negative or would extend the range beyond the end ofsource.
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
sourceT[]The array to copy and partially reverse.
rangeRangeThe 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 assource, where elements withinrangeappear in reverse order and all elements outsiderangeare copied unchanged.
Type Parameters
TThe 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
sourceis null.- ArgumentOutOfRangeException
Thrown when
rangeresolves to a start index that is negative or to an end index that exceedssource.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
| Product | Versions |
|---|---|
| .NET | 8, 10 |