Skip to content

API Proposal: String.{Try}CopyTo(Span<char>) #51061

@stephentoub

Description

@stephentoub

Background and Motivation

When working with text (strings and spans), it's relatively common to need to copy a string to a span, which can be done with:

string.AsSpan().CopyTo(destination)

We can make this simpler and faster by adding such a CopyTo directly to string:

string.CopyTo(destination)

Same with TryCopyTo. For example, Number.Formatting.cs in corelib has this:

private static bool TryCopyTo(string source, Span<char> destination, out int charsWritten)
{
Debug.Assert(source != null);
if (source.AsSpan().TryCopyTo(destination))
{
charsWritten = source.Length;
return true;
}
charsWritten = 0;
return false;
}

by changing the source.AsSpan().TryCopyTo(destination) there to source.TryCopyTo(destination) (with an implementation of TryCopyTo on string that's the same 7-line implementation on span), we get this diff:
image

Proposed API

namespace System
{
    public sealed class String
    {
        ...
        public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count);
+       public void CopyTo(Span<char> destination);
+       public bool TryCopyTo(Span<char> destination);
    }
}

Risks

string.AsSpan().{Try}CopyTo works with null input strings, because AsSpan() special-cases null to return an empty span. As a result, someone switching from the former to these new APIs could incur a null reference exception if they used a null string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedAPI was approved in API review, it can be implementedarea-System.RuntimeblockingMarks issues that we want to fast track in order to unblock other important work

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions