ArraySectionT Structure

Represents a one dimensional array or a section of an array. This type is very similar to ArraySegmentT/Memory<T> types but can be used on every platform in the same way, allows span-like operations such as slicing, and it is faster than Memory<T> in most cases. Depending on the used platform it supports ArrayPoolT allocation.

See the online help for examples.

Definition

Namespace: KGySoft.Collections
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 9.0.0
C#
[SerializableAttribute]
public struct ArraySection<T> : IList<T>, 
	ICollection<T>, IEnumerable<T>, IEnumerable, IList, ICollection, 
	IEquatable<ArraySection<T>>, IReadOnlyList<T>, IReadOnlyCollection<T>
Inheritance
Object    ValueType    ArraySectionT
Implements
ICollectionT, IEnumerableT, IListT, IReadOnlyCollectionT, IReadOnlyListT, ICollection, IEnumerable, IList, IEquatableArraySectionT

Type Parameters

T
The type of the elements in the collection.

Remarks

The ArraySectionT type is similar to the combination of the MemoryT type and the .NET Core version of the ArraySegmentT type.

In .NET Core 2.1/.NET Standard 2.1 and above an ArraySectionT instance can be easily turned to a SpanT instance (either by cast or by the AsSpan property), which is much faster than using the Span property of a MemoryT instance.

If an ArraySectionT is created by the constructor with a specified size, then depending on the size and the current platform the underlying array might be obtained by using the ArrayPoolT.

  Note

An ArraySectionT instance that was instantiated by the self allocating constructor must be released by calling the Release method when it is not used anymore. The ArraySectionT type does not implement IDisposable because releasing is not required when ArraySectionT is created from an existing array but not calling it when it would be needed may lead to decreased application performance.

Though ArraySectionT is practically immutable (has only readonly fields) it is not marked as readonly, which is needed for the Release method to work properly. As ArraySectionT is a non-readonly struct it is not recommended to use it as a readonly field; otherwise, accessing its members would make the pre-C# 8.0 compilers to create defensive copies, which leads to a slight performance degradation.

  Tip

  • You can always easily reinterpret an ArraySectionT instance as a two or three-dimensional array by the AsArray2D and AsArray3D methods without any allocation on the heap.
  • You can also reinterpret the element type by the Cast method that returns a CastArrayTFrom, TTo instance. Casts are also available as two or three-dimensional views by the Cast2D and Cast3D methods.

Examples

The following example demonstrates how to get various single and multidimensional views for an array without any heap allocation:
C#
// The actual underlying buffer we want to use.
var buffer = new byte[256];

// Note that none of the lines below allocate anything on the heap.

// So far similar to AsSpan or AsMemory extensions, but this is available on all platforms:
ArraySection<byte> section = buffer.AsSection(25, 100); // 100 bytes starting at index 25

// But if you wish you can treat it as a 10x10 two-dimensional array:
Array2D<byte> as2d = section.AsArray2D(10, 10); // an Array3D can be created in a similar way

// 2D indexing works the same way as for a real multidimensional array. But this is actually faster:
byte element = as2d[2, 3]; // row index first, then column index (similarly to regular arrays)

// Slicing works the same way as for ArraySection/Spans:
Array2D<byte> someRows = as2d[1..^1]; // same as as2d.Slice(1, as2d.Height - 2)

// Or you can get a simple row:
ArraySection<byte> singleRow = as2d[0];

// You can even reinterpret the element type if you whish:
CastArray<byte, Color32> asColors = section.Cast<byte, Color32>();

// Now you can access the elements cast to the reinterpreted type:
Color32 c = asColors[0];

// Or the reference to them (if supported by the compiler you use):
ref Color32 cRef = ref asColors.GetElementReference(0);

// Casts also have their 2D/3D counterparts:
CastArray2D<byte, Color32> asColors2D = asColors.As2D(height: 4, width: 6);

// Same as above, but directly from the section:
asColors2D = section.Cast2D<byte, Color32>(4, 6);

Constructors

ArraySectionT(T) Initializes a new instance of the ArraySectionT struct from the specified array. No heap allocation occurs when using this constructor overload.
ArraySectionT(ArraySegmentT) Initializes a new instance of the ArraySectionT struct from the specified ArraySegmentT. No heap allocation occurs when using this constructor overload.
ArraySectionT(T, Int32) Initializes a new instance of the ArraySectionT struct from the specified array using the specified offset. No heap allocation occurs when using this constructor overload.
ArraySectionT(Int32, Boolean) Initializes a new instance of the ArraySectionT struct using an internally allocated buffer.
When using this overload, the returned ArraySectionT instance must be released by the Release method if it is not used anymore.
ArraySectionT(T, Int32, Int32) Initializes a new instance of the ArraySectionT struct from the specified array using the specified offset and length. No heap allocation occurs when using this constructor overload.

Properties

AsArraySegment Returns the current ArraySectionT instance as an ArraySegmentT.
AsMemory Returns this ArraySectionT as a MemoryT instance.
AsSpan Returns this ArraySectionT as a SpanT instance.
IsNull Gets whether this ArraySectionT instance represents a array.
Please note that the ToArray method returns when this property returns .
IsNullOrEmpty Gets whether this ArraySectionT instance represents an empty array section or a array.
Item Gets or sets the element at the specified index.
Length Gets the number of elements in this ArraySectionT.
Offset Gets the offset, which denotes the start position of this ArraySectionT within the UnderlyingArray.
UnderlyingArray Gets the underlying array of this ArraySectionT.

Methods

AsArray2D Gets this ArraySectionT as an Array2DT instance using the specified height and width. The ArraySectionT must have enough capacity for the specified dimensions.
AsArray3D Gets this ArraySectionT as an Array3DT instance using the specified height and width. The ArraySectionT must have enough capacity for the specified dimensions.
CastTFrom, TTo Reinterprets this ArraySectionT by returning a CastArrayTFrom, TTo struct, so its element type is cast from TFrom to TTo. This method can be used only when T in this ArraySectionT is a value type that contains no references.
Cast2DTFrom, TTo Reinterprets this ArraySectionT as a two-dimensional CastArray2DTFrom, TTo struct, while its element type is cast from TFrom to TTo. This method can be used only when T in this ArraySectionT is a value type that contains no references.
Cast3DTFrom, TTo Reinterprets this ArraySectionT as a three-dimensional CastArray2DTFrom, TTo struct, while its element type is cast from TFrom to TTo. This method can be used only when T in this ArraySectionT is a value type that contains no references.
Clear Clears the items in this ArraySectionT instance so all elements will have the default value of type T. To clear the items with a specific value use the Fill method instead.
Contains Determines whether this ArraySectionT contains the specific item.
CopyTo(ArraySectionT) Copies the items of this ArraySectionT to a compatible instance.
CopyTo(T, Int32) Copies the items of this ArraySectionT to a compatible one-dimensional array, starting at a particular index.
Equals(ArraySectionT) Indicates whether the current ArraySectionT instance is equal to another one specified in the other parameter. That is, when they both reference the same section of the same UnderlyingArray instance.
Equals(Object) Determines whether the specified object is equal to this instance.
(Overrides ValueTypeEquals(Object))
Fill Assigns the specified value to all elements in this ArraySectionT instance.
GetElementReference Gets the reference to the element at the specified index.
GetElementReferenceUnchecked Gets the reference to the element at the specified index, allowing it to point to any element in the UnderlyingArray. To validate index against Length use the GetElementReference method instead. This method does not perform any validation, so it can even throw a NullReferenceException if the IsNull property returns .
GetElementUnchecked Gets the element at the specified index, allowing it to point to any element in the UnderlyingArray. To validate index against Length use the indexer instead. This method does not perform any validation, so it can even throw a NullReferenceException if the IsNull property returns .
GetEnumerator Returns an enumerator that iterates through the items of this ArraySectionT.
GetHashCode Returns a hash code for this ArraySectionT instance.
(Overrides ValueTypeGetHashCode)
GetPinnableReference Returns a reference to the first element in this ArraySectionT. This makes possible to use the ArraySectionT in a fixed statement.
IndexOf Determines the index of a specific item in this ArraySectionT.
Release Releases the underlying array. If this ArraySectionT instance was instantiated by the self allocating constructor, then this method must be called when the ArraySectionT is not used anymore. On platforms that do not support the ArrayPoolT class this method simply sets the self instance to Null.
SetElementUnchecked Sets the element at the specified index, allowing it to point to any element in the UnderlyingArray. To validate index against Length use the indexer instead. This method does not perform any validation, so it can even throw a NullReferenceException if the IsNull property returns .
Slice(Int32) Gets a new ArraySectionT instance, which represents a subsection of the current instance with the specified startIndex.
Slice(Int32, Int32) Gets a new ArraySectionT instance, which represents a subsection of the current instance with the specified startIndex and length.
ToArray Copies the elements of this ArraySectionT to a new array.

Operators

Equality(ArraySectionT, ArraySectionT) Determines whether two specified ArraySectionT instances have the same value.
(T to ArraySectionT) Performs an implicit conversion from array of T to ArraySectionT.
(ArraySectionT to ArraySegmentT) Performs an implicit conversion from ArraySectionT to ArraySegmentT.
(ArraySectionT to SpanT) Performs an implicit conversion from ArraySectionT to SpanT.
(ArraySegmentT to ArraySectionT) Performs an implicit conversion from ArraySegmentT to ArraySectionT.
Inequality(ArraySectionT, ArraySectionT) Determines whether two specified ArraySectionT instances have different values.

Fields

Empty Represents the empty ArraySectionT. This field is read-only.
Null Represents the  ArraySectionT. This field is read-only.

Extension Methods

AddRangeT Adds a collection to the target ICollectionT.
(Defined by CollectionExtensions)
AsThreadSafeT Returns a LockingListT, which provides a thread-safe wrapper for the specified list. This only means that if the members are accessed through the returned LockingListT, then the inner state of the wrapped list remains always consistent and not that all the multi-threading concerns can be ignored.
See the Remarks section of the LockingListT class for details and some examples.
(Defined by ListExtensions)
AsThreadSafeT Returns a LockingCollectionT, which provides a thread-safe wrapper for the specified collection. This only means that if the members are accessed through the returned LockingCollectionT, then the inner state of the wrapped collection remains always consistent and not that all the multi-threading concerns can be ignored.
See the Remarks section of the LockingCollectionT class for details and some examples.
(Defined by CollectionExtensions)
Convert Converts an Object specified in the obj parameter to the desired targetType.
See the Examples section of the generic ConvertTTarget(Object, CultureInfo) overload for an example.
(Defined by ObjectExtensions)
ConvertTTarget Converts an Object specified in the obj parameter to the desired TTarget.
(Defined by ObjectExtensions)
ForEachT Similarly to the List<T>.ForEach method, processes an action on each element of an enumerable collection.
(Defined by EnumerableExtensions)
GetRandomElementT Gets a random element from the enumerable source using a new FastRandom instance.
(Defined by EnumerableExtensions)
GetRandomElementT Gets a random element from the enumerable source using a specified Random instance.
(Defined by EnumerableExtensions)
In Gets whether item is among the elements of set.
See the Examples section of the generic InT(T, T) overload for an example.
(Defined by ObjectExtensions)
IndexOf Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions)
IndexOf Searches for an element in the source enumeration.
(Defined by EnumerableExtensions)
IndexOfT Searches for an element in the source enumeration.
(Defined by EnumerableExtensions)
IndexOfT Searches for an element in the source enumeration where the specified predicate returns .
(Defined by EnumerableExtensions)
InsertRangeT Inserts a collection into the target IListT.
(Defined by ListExtensions)
IsNullOrEmpty Determines whether the specified source is or empty (has no elements).
(Defined by EnumerableExtensions)
IsNullOrEmptyT Determines whether the specified source is or empty (has no elements).
(Defined by EnumerableExtensions)
JoinT Concatenates the items of the source collection into a new string instance using the specified separator between the items.
(Defined by EnumerableExtensions)
JoinT Concatenates the items of the source collection into a new string instance using the specified separator between the items.
(Defined by EnumerableExtensions)
RemoveRangeT Removes count amount of items from the specified collection at the specified index.
(Defined by ListExtensions)
ReplaceRangeT Removes count amount of items from the target IListT at the specified index, and inserts the specified collection at the same position. The number of elements in collection can be different from the amount of removed items.
(Defined by ListExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using the provided seed with a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using the provided seed with a new FastRandom instance.
(Defined by EnumerableExtensions)
ShuffleT Shuffles an enumerable source (randomizes its elements) using a specified Random instance.
(Defined by EnumerableExtensions)
ToCircularListT Creates a CircularListT from an IEnumerableT.
(Defined by EnumerableExtensions)
ToStringKeyedDictionaryT Creates a StringKeyedDictionaryTValue from an IEnumerableT instance using the specified keySelector delegate and a comparer.
(Defined by EnumerableExtensions)
ToStringKeyedDictionaryT, TValue Creates a StringKeyedDictionaryTValue from an IEnumerableT instance using the specified key and value selector delegates and a comparer.
(Defined by EnumerableExtensions)
TryAdd Tries to add the specified item to the collection.
(Defined by EnumerableExtensions)
TryAddT Tries to add the specified item to the collection.
(Defined by EnumerableExtensions)
TryAddRange Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions)
TryAddRangeT Tries to add the specified collection to the target collection.
(Defined by EnumerableExtensions)
TryClear Tries to remove all elements from the collection.
(Defined by EnumerableExtensions)
TryClearT Tries to remove all elements from the collection.
(Defined by EnumerableExtensions)
TryConvert Tries to convert an Object specified in the obj parameter to the desired targetType.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvert Tries to convert an Object specified in the obj parameter to the desired targetType.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvertTTarget Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryConvertTTarget Tries to convert an Object specified in the obj parameter to the desired TTarget.
See the Examples section of the ConvertTTarget(Object, CultureInfo) method for a related example.
(Defined by ObjectExtensions)
TryGetCount Tries to get the number of elements in the source enumeration without enumerating it.
(Defined by EnumerableExtensions)
TryGetCountT Tries to get the number of elements in the source enumeration without enumerating it.
(Defined by EnumerableExtensions)
TryGetElementAt Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions)
TryGetElementAtT Tries to get an item at the specified index in the collection.
(Defined by EnumerableExtensions)
TryInsert Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions)
TryInsertT Tries to insert the specified item at the specified index to the collection.
(Defined by EnumerableExtensions)
TryInsertRange Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions)
TryInsertRangeT Tries to insert the specified collection into the target collection.
(Defined by EnumerableExtensions)
TryRemove Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions)
TryRemoveT Tries to remove the specified item from to the collection.
(Defined by EnumerableExtensions)
TryRemoveAt Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions)
TryRemoveAtT Tries to remove an item at the specified index from the collection.
(Defined by EnumerableExtensions)
TryRemoveRange Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions)
TryRemoveRangeT Tries to remove count amount of items from the specified collection at the specified index.
(Defined by EnumerableExtensions)
TryReplaceRange Tries to remove count amount of items from the target at the specified index, and to insert the specified collection at the same position. The number of elements in collection can be different from the amount of removed items.
(Defined by EnumerableExtensions)
TryReplaceRangeT Tries to remove count amount of items from the target at the specified index, and to insert the specified collection at the same position. The number of elements in collection can be different from the amount of removed items.
(Defined by EnumerableExtensions)
TrySetElementAt Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions)
TrySetElementAtT Tries to set the specified item at the specified index in the collection.
(Defined by EnumerableExtensions)

See Also