Skip to content

Implicit span conversions C# 14.0code reductionperformance

Implicitly convert arrays and strings to spans without explicit casting.

Working with Span<T> and ReadOnlySpan<T> required explicit conversions or method calls to convert from arrays and strings, even though these conversions are safe and common. This added verbosity to performance-critical code.

C# 14.0 introduces implicit conversions from arrays to Span<T> and from strings to ReadOnlySpan<char>, making span-based APIs easier to use and reducing boilerplate in high-performance scenarios.

Code

C#
void ProcessData(ReadOnlySpan<int> data)
{
    // Process the data
}

void ProcessText(ReadOnlySpan<char> text)
{
    // Process the text
}

// Implicit conversions
int[] numbers = { 1, 2, 3, 4, 5 };
ProcessData(numbers); // Implicitly converts to ReadOnlySpan<int>

string message = "Hello, World!";
ProcessText(message); // Implicitly converts to ReadOnlySpan<char>

// Also works with Span<T>
void ModifyData(Span<int> data)
{
    data[0] = 100;
}

ModifyData(numbers); // Implicitly converts to Span<int>
C#
void ProcessData(ReadOnlySpan<int> data)
{
    // Process the data
}

void ProcessText(ReadOnlySpan<char> text)
{
    // Process the text
}

// Required explicit conversions
int[] numbers = { 1, 2, 3, 4, 5 };
ProcessData(numbers.AsSpan()); // Explicit conversion

string message = "Hello, World!";
ProcessText(message.AsSpan()); // Explicit conversion

// Also needed for Span<T>
void ModifyData(Span<int> data)
{
    data[0] = 100;
}

ModifyData(numbers.AsSpan()); // Explicit conversion

Notes

  • Arrays implicitly convert to both Span<T> and ReadOnlySpan<T>
  • Strings implicitly convert to ReadOnlySpan<char> only (strings are immutable)
  • No performance overhead - these are safe, efficient conversions
  • Makes span-based APIs more ergonomic and easier to adopt
  • Existing code using explicit conversions continues to work
  • Particularly useful for library authors designing high-performance APIs

More information