🎓 A1Learner
🔍
0 of 28 lessons completed

C# Span Basics

A Span<T> is a view over a contiguous run of elements, such as part of an array. Writes through the span change the data under it, and the span copies nothing.

Write Through a Span

A span covers the whole array. Writing span[0] changes the first element of the array itself.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 10, 20, 30 };
        Span<int> span = data;

        span[0] = 99;

        Console.WriteLine(data[0]);
    }
}

A Slice of the Data

Slice(1, 2) starts at index 1 and covers two elements. Main prints the two elements of the slice, one per line.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 5, 7, 10, 20 };
        Span<int> span = data;
        Span<int> part = span.Slice(1, 2);

        Console.WriteLine(part[0]);
        Console.WriteLine(part[1]);
    }
}

Find and Measure

IndexOf reports the position of the value 9 inside the span. Length reports how many elements the span covers.

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 4, 9, 6 };
        Span<int> span = data;

        Console.WriteLine(span.IndexOf(9));
        Console.WriteLine(span.Length);
    }
}

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        int[] data = { 0, 3, 4, 5, 0 };
        Span<int> span = data;

        int first = 0;

        while (span[first] == 0)
        {
            first++;
        }

        int last = span.Length - 1;

        while (span[last] == 0)
        {
            last--;
        }

        Span<int> middle = span.Slice(first, last - first + 1);

        int sum = 0;

        foreach (int n in middle)
        {
            sum += n;
        }

        Console.WriteLine(sum);
    }
}

Key points

  • A Span<int> over an array views the elements of that array.
  • An index into the span reads or writes the element at that position.
  • A write through the span changes the underlying array.
  • The Slice method returns a smaller span over part of the same data.
  • The Length property gives the number of elements the span covers.
  • The IndexOf method returns the position of a value, counted from the start of the span.

In this example, the code finds the first non-zero entry at index 1 and the last non-zero entry at index 3. Slice builds a span over those three entries. The loop adds 3, 4, and 5, and Main prints the sum 12.

Note

A span is a view, so two spans over one array see the same elements.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What happens when code writes through a Span<int> that covers an array?