Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

MemoryExtensions.AsSpan and IndexOf: searching a text view

Create a view of text without copying it, search for an element or sequence, and print the matching slice through `Console.Out.Write` without creating a substring.

Version: C# 12 and .NET 8; later runtimes may add compatible features

Syntax

using System;

// Selected .NET 8 signatures, declared in System.MemoryExtensions:
public static ReadOnlySpan<char> AsSpan(this string? text);
public static ReadOnlySpan<char> AsSpan(this string? text, int start);
public static ReadOnlySpan<char> AsSpan(this string? text, int start, int length);
public static Span<T> AsSpan<T>(this T[]? array);
public static int IndexOf<T>(this ReadOnlySpan<T> span, T value) where T : IEquatable<T>?;
public static int IndexOf<T>(this ReadOnlySpan<T> span, ReadOnlySpan<T> value) where T : IEquatable<T>?;
public static int IndexOf(this ReadOnlySpan<char> span, ReadOnlySpan<char> value, StringComparison comparisonType);

// Equivalent calls when the extension methods are in scope:
ReadOnlySpan<char> view = text.AsSpan(start, length);
ReadOnlySpan<char> sameView = System.MemoryExtensions.AsSpan(text, start, length);
int index = view.IndexOf('=');
int sameIndex = System.MemoryExtensions.IndexOf<char>(view, '=');

// Output uses a virtual instance method on System.IO.TextWriter:
Console.Out.Write(view);

MemoryExtensions.AsSpan/IndexOf refers to static extension methods on System.MemoryExtensions. With using System;, text.AsSpan() is shorthand for MemoryExtensions.AsSpan(text), and view.IndexOf('=') is shorthand for MemoryExtensions.IndexOf<char>(view, '='). These are not instance methods of string and ReadOnlySpan<char>, respectively. string.IndexOf is a separate instance method that searches the string itself.

AsSpan() returns a ReadOnlySpan<char> over the whole string, AsSpan(start) views it from start to the end, and AsSpan(start, length) views the specified length from start. The view neither copies the data nor lets you write through it. The no-offset AsSpan() returns an empty view for null; invalid bounds on a non-null string throw ArgumentOutOfRangeException. In contrast, AsSpan<T>(T[]) returns a writable Span<T> over the array.

The generic IndexOf<T> overloads look for one T or a contiguous ReadOnlySpan<T> sequence using IEquatable<T>.Equals for element comparison. There are also overloads with a Span<T> receiver. For a char sequence you can specify StringComparison; use Ordinal for case-sensitive, culture-independent matching. The result is the first zero-based index relative to the view, or -1 if there is no match. Text indexes count UTF-16 code units, not user-perceived characters. Check >= 0 before using the result to index or slice.

Slice is an instance method that produces a narrower view. Console.Out is a System.IO.TextWriter, so Console.Out.Write(view) calls its virtual instance method Write(ReadOnlySpan<char>) without adding a newline. The caller doesn't need to create a substring; that doesn't guarantee that the writer itself never allocates.

In C# 12, ReadOnlySpan<T> is a ref struct: you can't store it in a class field, box it, or declare a variable of that type in an async method. The example is synchronous and targets .NET 8; later runtimes may add compatible features.

Examples

using System;

const string input = "log:name=ada";
ReadOnlySpan<char> field = input.AsSpan(4, 8);

int separator = field.IndexOf('=');
int name = MemoryExtensions.IndexOf(field, "ada".AsSpan(), StringComparison.Ordinal);
int missing = field.IndexOf(':');

Console.WriteLine(FormattableString.Invariant($"{separator} {name} {missing}"));
if (separator >= 0)
{
    ReadOnlySpan<char> value = field.Slice(separator + 1);
    Console.Out.Write(value);
    Console.Out.WriteLine();
}

Result

4 5 -1
ada

The view contains `name=ada`: `=` is at index `4`, `ada` starts at `5`, and `:` occurs only in the skipped prefix, so that search returns `-1`. `Slice(separator + 1)` selects `ada` for `Console.Out.Write`.

Related lessons

  • C# · Lesson 9 · Advanced · Version: 3

Sources