loading experience

C#

Span and ReadOnlySpan in C# 14: implicit conversions

Arrays and strings become Spans without casts: cleaner code and high-performance APIs that are easier to use.

Span and ReadOnlySpan in C# 14: implicit conversions

Span<T> and ReadOnlySpan<T> represent a contiguous region of memory without copying it: they are the foundation of high-performance .NET code. C# 14 makes them "first-class citizens" with new implicit conversions.

Implicit conversions bring arrays and strings to span-based APIs.
Implicit conversions bring arrays and strings to span-based APIs.

What changes

An array can be implicitly converted to Span<T> and ReadOnlySpan<T>, and the compiler also considers these conversions when looking up extension methods. The result: extensions written for ReadOnlySpan<T> can be called directly on an array.

public static class SpanExtensions
{
    public static int CountEven(this ReadOnlySpan<int> values)
    {
        var n = 0;
        foreach (var v in values) if (v % 2 == 0) n++;
        return n;
    }
}

int[] numbers = [1, 2, 3, 4, 5, 6];
Console.WriteLine(numbers.CountEven()); // 3, no .AsSpan()

Why it helps

  • You write a single version of the method for arrays, strings and memory slices.
  • You avoid copies: working on a slice with values[2..5] allocates nothing.
  • Libraries can offer span-based overloads, which the compiler prefers automatically.

An example with strings

ReadOnlySpan<char> line = "2026-10-10;order;42";
var first = line.IndexOf(';');
var date = line[..first];          // no new string
Console.WriteLine(date.ToString()); // 2026-10-10

One caveat: spans live only on the stack and cannot be stored in class fields or used across await. For those cases there is Memory<T>.

Comments (0)

No comments yet.

Leave a comment