Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C#

TextWriter.Write(ReadOnlySpan<char>) — writing a text slice

TextWriter.Write(ReadOnlySpan<char>) writes characters from a memory view without appending a line terminator. It lets the caller pass a text slice without creating a substring, but does not guarantee allocation-free writing inside a particular writer.

Version: .NET 10; repository net10.0 and LangVersion=preview; feature versions require per-entry verification

Syntax

public virtual void Write(ReadOnlySpan<char> buffer);

TextWriter.Write(ReadOnlySpan<char>) is a synchronous, virtual overload in the System.IO namespace. It writes the characters in buffer to the destination text stream and returns void. Unlike WriteLine, it does not append a line terminator; it is also not an overload accepting a format string and arguments.

ReadOnlySpan<char> is a read-only view of characters. Calling text.AsSpan(1, 5) selects five characters starting at index 1 without creating a separate substring. Pass this view directly to Write; calling ToString() first is unnecessary. The index and length must be within the text's bounds.

The method is virtual: the writer's runtime type determines the implementation, even when the variable is typed as TextWriter. Using the span overload alone does not guarantee that the writer performs no allocations or internal copying. Distinguish avoiding a substring at the call site from the cost of writing to the destination.

This API has been available since .NET Core 2.1 and in .NET Standard 2.1, and remains available in .NET 10; it is not new in .NET 10. The example targets the repository's net10.0 and LangVersion=preview configuration. It uses StringWriter through a TextWriter reference: it writes the slice hello, then !, and finally prints hello! without a line terminator.

Examples

using System;
using System.IO;

using StringWriter storage = new StringWriter();
TextWriter writer = storage;

string text = "[hello]";
ReadOnlySpan<char> part = text.AsSpan(1, 5);
writer.Write(part);
writer.Write('!');

Console.Write(storage.ToString());

Result

hello!

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources