Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

Search, compare, and parse span views

Use spans to search and compare existing text without copying it, then parse fields as `int` or `decimal` with explicit format rules.

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

Syntax

using System;
using System.Globalization;

// Selected call forms for C# 12 / .NET 8:
ReadOnlySpan<char> text = sourceString.AsSpan();
ReadOnlySpan<char> part = sourceString.AsSpan(start, length);
Span<int> elements = sourceArray.AsSpan(); // sourceArray is int[]
int elementIndex = text.IndexOf(':');
int sequenceIndex = text.IndexOf(needle); // needle is ReadOnlySpan<char>
int textIndex = text.IndexOf(needle, StringComparison.OrdinalIgnoreCase);
bool same = text.SequenceEqual(needle);
bool sameIgnoringCase = MemoryExtensions.Equals(text, needle, StringComparison.OrdinalIgnoreCase);
bool intOk = int.TryParse(part, NumberStyles.None, CultureInfo.InvariantCulture, out int count);
bool decimalOk = decimal.TryParse(part, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out decimal price);

In C# 12 and .NET 8, MemoryExtensions.AsSpan/IndexOf/SequenceEqual are extension methods available through using System;. AsSpan() creates a view without copying: a string gives a ReadOnlySpan<char>, and a T[] gives a writable Span<T>. The array overload AsSpan<T> throws ArrayTypeMismatchException when an array is passed covariantly, for example when a string[] is passed as an object[]. AsSpan(start, length) selects a slice; invalid bounds on a non-null source throw ArgumentOutOfRangeException. Calling the parameterless form on a null string gives an empty view. Both span types are ref struct types: a view must not outlive its backing storage, and C# 12 does not allow span locals in async methods or iterators.

IndexOf looks for one element or a contiguous sequence. It returns the first zero-based index relative to the searched view, or -1 if not found; an empty sequence returns 0. Check the result before slicing. The generic overloads shown use IEquatable<T>; for char they compare UTF-16 code units. This is not String.IndexOf: its string overload uses the current culture by default, while its char overload is ordinal. For a case-insensitive search on a text span, use the overload with StringComparison.OrdinalIgnoreCase.

SequenceEqual requires equal lengths and equal elements in corresponding positions. For char spans the call shown is case-sensitive and does not normalize Unicode; for case-insensitive equality use MemoryExtensions.Equals with StringComparison.OrdinalIgnoreCase. Span == checks the starting memory location and length, not contents. LINQ's System.Linq.Enumerable.SequenceEqual works on IEnumerable<T>, not spans. Do not assume SequenceEqual is constant-time; for equal-length secret byte data, use CryptographicOperations.FixedTimeEquals.

int.TryParse and decimal.TryParse accept ReadOnlySpan<char> without creating a substring. Choose NumberStyles and a culture that match the input format: here NumberStyles.None enables no optional format features, while NumberStyles.AllowDecimalPoint permits a decimal separator, which is . in CultureInfo.InvariantCulture. In .NET 8, both parsers ignore trailing U+0000 characters even with these settings. If your format forbids them, reject them explicitly before parsing. Use the out value only after true; an empty field or an integer overflow returns false, but an invalid NumberStyles value can throw.

Examples

using System;
using System.Globalization;

ReadOnlySpan<char> record = "item:42;19.95".AsSpan();
int colon = record.IndexOf(":".AsSpan());
if (colon < 0 || !record[..colon].SequenceEqual("item".AsSpan()))
{
    Console.WriteLine("Invalid record.");
    return;
}

ReadOnlySpan<char> fields = record[(colon + 1)..];
int separator = fields.IndexOf(';');
var culture = CultureInfo.InvariantCulture;
if (separator < 0 ||
    !int.TryParse(fields[..separator], NumberStyles.None, culture, out int count) ||
    !decimal.TryParse(fields[(separator + 1)..], NumberStyles.AllowDecimalPoint, culture, out decimal price))
{
    Console.WriteLine("Invalid record.");
    return;
}

Console.WriteLine(FormattableString.Invariant($"count={count}; price={price:0.00}"));

Result

count=42; price=19.95

The program checks the `item` label, finds both separators, and parses two fields without creating substrings. The semicolon index is relative to `fields`, not `record`.

Related lessons

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

Sources