Span<T>.Enumerator Struct in C#
Span<T> is a new feature introduced with C# 7.2 and supported in the .NET Core 2.1. It provides a type-safe access to a contiguous area of memory. This memory can be located on the heap, stack or formed a unallocated memory. Span<T> is defined as a ref struct, which means it is limited to being allocated only on the Stack. The main reason for the ref struct design is to ensure that when using of Span<T> it causes no additional heap allocations. Span<T> improves execution speed and reducing memory allocations in existing code.
Here, Span<T> references some contiguous memory(colored blocks) that has already been allocated.
Span<T>.Enumerator struct provides an enumerator for the elements of a Span<T>. Where Span<T> provides a type and memory safe representation of a contiguous region of arbitrary memory.
Syntax:
public struct Span<T>.Enumerator
Parameter:
Here the parameter is T, where T is the type of items in the Span<T>.
Example:
csharp
// C# program to demonstrate Span<T>.Enumerator Struct using System; using System.Threading.Tasks; class GFG { // a array "arr" type of byte private static byte [] arr = new byte [4]; // main method static void Main() { // randomly fillup the array "arr" new Random(30).NextBytes(arr); // implicitly cast the array // "arr" to span<byte> Span< byte > sp = arr; // Task.Run() method executes // the clear() method // to clear the array for // each thread operations Task.Run(() => clear()); // call the function "print" print(sp); } public static void clear() { // delay for 10ms Task.Delay(10).Wait(); lock (arr) // defines that one thread // executes one task at one time { Array.Clear(arr, 0, arr.Length); } } // print function public static void print(Span< byte > span) { foreach ( byte e in span) { Console.WriteLine(e); Task.Delay(10).Wait(); } } } |
Output:
52 239 0 0
Properties:
- Current: It is used to get a reference to the item at the current position of the enumerator.
Methods:
- MoveNext(): It advances the enumerator to the next item of the Span<T>.
Important Points:
- Span<T> provides a type-safe access to a contiguous area of memory.
- It cannot be used within asynchronous methods.
- It does not implement the IEnumerator or IEnumerator<T> interface, because Span<T> enumerator is a ref struct.
- It does not include a Reset method.
- For use the Reset() method, it must be implemented as part of the interface.
- It does not include additional heap allocation.
- It cannot be used as a generic type argument.
- Span<T> provides read-write access to the memory.
- ReadOnlySpan<T> provides read-only access to a memory.