Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The Span2D<T> class mirrors the functionality of the Span<T> type, but it supports 2D memory regions. Like Memory2D<T>, it's extremely flexible and can wrap a number of different objects, as well as native pointers or GC references.
The internal layout is similar to the layout used by the Memory2D<T> type. It includes a pitch parameter that enables support for discontiguous memory buffers. You can read more about this in the Memory2D<T> docs.
Platform APIs:
Span2D<T>,Memory2D<T>,ReadOnlySpan2D<T>
Syntax
Here's how you create a Span2D<T> instance from a 2D array:
int[,] array =
{
{ 1, 2, 3 },
{ 4, 5, 6 }
};
Span2D<int> span = array;
// The memory directly maps the 2*3 array here
span[0, 0] = 10;
span[1, 1] = 20;
// The array is now:
// { 10, 2, 3 },
// { 4, 20, 6 }
// We can also use indices, on supported runtimes
int x = span[0, ^1];
// We can also get references to items, like with arrays
ref int reference = ref span[1, 1];
Span2D<int> slice = span.Slice(0, 1, 2, 2);
// Or alternatively, on supported runtimes
slice = span[.., 1..];
int[,] copy = slice.ToArray();
// The resulting array is:
// { 2, 3 },
// { 20, 6 }
You can also directly create a 2D view over native memory:
int* p = stackalloc int[9];
Span2D<int> span = new Span2D<int>(p, 3, 3);
The Span2D<T> type includes custom enumerator types to easily traverse a given row, column, or the entire memory area by using the standard foreach syntax in C#. It also supports performing bulk operations in a single call:
int[,] array =
{
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
Span2D<int> span = array;
foreach (int i in span.GetColumn(1))
{
// 2, 5, 8
}
// We can also iterate by reference
foreach (ref int i in span.GetRow(2))
{
// 7, 8, 9
}
foreach (int i in span)
{
// 1, 2, 3, 4, 5...
}
// Set all items in a column to 0
span.GetColumn(0).Clear();
// Set the value of all items in a row
span.GetRow(1).Fill(42);
Span<int> copy = stackalloc int[3];
// Copy all items from a column
span.GetColumn(2).CopyTo(copy);
// Get a copy of a row as an array
int[] array = span.GetRow(1).ToArray();
ReadOnlySpan2D<T>
The ReadOnlySpan2D<T> type is to the Span2D<T> type what ReadOnlySpan<T> is to Span<T>. It exposes a similar set of APIs but provides no way to directly modify the contents of the underlying memory area.
Sample code
You can find more examples in the unit tests.
.NET Community Toolkit