Skip to content

[API Proposal]: Implement ISpanFormattable on StringBuilder #105870

Description

@karakasa

Background and motivation

See #105775.

Implementing ISpanFormattable on StringBuilder could reduce string allocations when StringBuilder is being used in interpolated strings & string.Join.

API Proposal

namespace System.Text;

public partial class StringBuilder : IFormattable, ISpanFormattable
{
        public bool TryFormat(Span<char> destination, out int charsWritten);

        // Do we also want, to match: ToString(int startIndex, int length)?
        // public bool TryFormat(Span<char> destination, int startIndex, int length, out int charsWritten);

        bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider);

        string IFormattable.ToString(string? format, IFormatProvider? formatProvider);
}
  • Two added methods are implemented explicitly.
  • The implementation itself is trival, similar to System.Uri.

API Usage

StringBuilder SomeStringBuilder = ...;
var interpolatedString = $"aa {SomeStringBuilder} bb";

In such cases, DefaultInterpolatedStringHandler and other handlers will use TryFormat() rather than ToString().

Alternative Designs

Treat StringBuilder as special cases in interpolated string handlers.

Risks

This change shouldn't break any normal use cases. But we need to ensure the following edge case doesn't bug (resulting in infinite loops, etc).

public void M(StringBuilder s) {
    s.Append($"aa{s}bb");
}

Activity

  1. added
    api-suggestion
    on Aug 2, 2024
  2. ghost added
    needs-area-label
    on Aug 2, 2024
  3. added
    untriaged
    on Aug 2, 2024
  4. added and removed
    needs-area-label
    on Aug 2, 2024
  5. dotnet-policy-service commented on Aug 2, 2024

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-runtime
    See info in area-owners.md if you want to be subscribed.

  6. added
    needs-further-triage
    and removed
    untriaged
    on Aug 6, 2024
  7. added this to the Future milestone on Aug 6, 2024
  8. Neme12 commented on Oct 18, 2026

    @Neme12

    Why is this issue completely inactive? This is a useful perf addition with lots of upvotes and noone even commented.

  9. tannergooding commented on Oct 18, 2026

    @tannergooding
    Member

    @Neme12 we get thousands of issues and PRs created each release, things sometimes get lost in the noise. This is especially true with competing prioritization, people moving around, etc.

    Then I'd note a thumbs up provides no notification and so it stays on the general backlog. People actually commenting and giving a concrete scenario where it provides benefit is a different story. -- That is not to say people should jump in with "me too" style comments. It is rather stating that people giving a short summary of a concrete scenario they found this would be beneficial can help.

    Convenience style APIs are also notably often lower priority. People aren't prevented from using interpolated string handlers + string builder in an allocation free manner, it's just a pain because you can no longer trivially use the friendly language syntax and need to jump through hoop.

  10. added
    api-ready-for-review
    and removed
    api-suggestion
    needs-further-triage
    on Oct 18, 2026
  11. modified the milestones: Future, 12.0.0 on Oct 18, 2026
  12. Neme12 commented on Oct 18, 2026

    @Neme12

    TextWriter should implement it as well. I have a use case for that too.

  13. Neme12 commented on Oct 18, 2026

    @Neme12

    @karakasa Would you please modify the issue and add TextWriter as well?

  14. Neme12 commented on Oct 18, 2026

    @Neme12

    Also, I think the public method should not take ReadOnlySpan<char> format, IFormatProvider? provider. Only the explicit interface implementation would need them.

  15. Neme12 commented on Oct 18, 2026

    @Neme12

    Actually, maybe we don't have to have a public method at all and only explicit interface implementation, because there's already CopyTo, which does the same thing. Though there's no TryCopyTo.

  16. Neme12 commented on Oct 18, 2026

    @Neme12

    @tannergooding Thanks very much for marking this as ready for review. We should still flesh out the proposal a bit though (public methods vs no public methods etc), but maybe the original author won't see this anymore since it's been years.

  17. tannergooding commented on Oct 19, 2026

    @tannergooding
    Member

    The question of public vs not can be solved in API review and I'll ensure its updated appropriately.

    It really doesn't really change anything concrete here; just a minor nuance on "is the interface API implicit or explicit" and "if explicit, do we expose the convenient API that hides the unused parameters as is standard"

    For TextWriter or any other types, those should be proposals for their own areas as they have distinct area owners and considerations.

  18. bartonjs commented on Nov 3, 2026

    @bartonjs
    Member

    Video

    • Let's preemptively add IUtf8SpanFormattable
    • We've mirrored the partial-copy capability of ToString(startIndex, length) with TryFormat(destination, sourceRange)
    namespace System.Text;
    
    public partial class StringBuilder : IFormattable, ISpanFormattable, IUtf8SpanFormattable
    {
        public bool TryFormat(Span<char> destination, out int charsWritten);
        public bool TryFormat(Span<char> destination, Range sourceRange, out int charsWritten);
    
        public bool TryFormat(Span<byte> utf8Destination, out int bytesWritten);
        public bool TryFormat(Span<byte> utf8Destination, Range sourceRange, out int bytesWritten);
    
        string IFormattable.ToString(string? format, IFormatProvider? formatProvider);
        bool ISpanFormattable.TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider);
        bool IUtf8SpanFormattable.TryFormat(Span<byte> utf8Destination, out int bytesWritten, ReadOnlySpan<char> format, IFormatProvider? provider);
    }
  19. added
    api-approved
    and removed
    api-ready-for-review
    on Nov 3, 2026
  20. Manish-1kumar commented on Nov 5, 2026

    @Manish-1kumar
    Contributor

    I'd like to take this one and will open a PR implementing the approved API, including IUtf8SpanFormattable and the TryFormat overloads with a source range, plus tests for the self-append case (sb.Append($"aa{sb}bb")) mentioned in the proposal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.Runtime

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions