bhylu.com

Advertisements

C# Span<T>

Use a read-only view for a synchronous calculation without copying the array.

How it works

ReadOnlySpan<T> describes a contiguous range without owning its storage. Span<T> permits writes through the view. These ref-like types have compiler-enforced lifetime restrictions that make many unsafe escapes impossible, but callers still need valid bounds and an ownership model. They are useful for short synchronous parsing and slicing. Memory<T> can cross different asynchronous boundaries, but does not itself own or freeze an arbitrary backing owner’s lifetime.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;

internal static class Program
{
    private static void Main(string[] args)
    {
        int[] counts = { 3, 4, 5 };
        Console.WriteLine($"Total: {Total(counts)}");
        ReadOnlySpan<int> middle = counts.AsSpan(1, 1);
        Console.WriteLine($"Middle: {middle[0]}");
    }

    internal static int Total(ReadOnlySpan<int> values)
    {
        int total = 0;
        foreach (int value in values) total = checked(total + value);
        return total;
    }
}

Expected result

Total: 12
Middle: 4

The array remains alive while the views are used. The total helper checks arithmetic and accepts an empty range with total zero. A view’s Length describes accessible elements, not independent storage. This example does not retain a span across await or store it in an ordinary class field; newer language rules still require lifetime-safe use under the selected compiler.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.