Skip to content

Proposal: adding Append overloads with format and IFormatProvider to StringBuilder #50674

@Wojmik

Description

@Wojmik

Background and Motivation

StringBuilder is easy to use and powerful api. It is often used to serialize some data - eg. to text file. This data commonly have to be in InvariantCulture and have specific format.

Sadly currently there is no way to append primitive value types like double or DateTime with format and IFormatProvider without unnecessary allocation. You can use AppendFormat but value is object so there is a boxing. You can use Append but there is no format nor IFormatProvider parameter.

All existing Append methods use this method internally:

private StringBuilder AppendSpanFormattable<T>(T value) where T : ISpanFormattable

But there is already another overload of this method that can be used:

 internal StringBuilder AppendSpanFormattable<T>(T value, string? format, IFormatProvider? provider) where T : ISpanFormattable, IFormattable

I don't known if there is another boxing here because of interface use (ISpanFormattable) on struct by the way.

I think I can make these changes, it shouldn't be hard anyway.

Proposed API

Add the following overloads to StringBuilder:

Append(byte value, string? format, IFormatProvider? provider);
Append(sbyte value, string? format, IFormatProvider? provider);
Append(short value, string? format, IFormatProvider? provider);
Append(ushort value, string? format, IFormatProvider? provider);
Append(int value, string? format, IFormatProvider? provider);
Append(uint value, string? format, IFormatProvider? provider);
Append(long value, string? format, IFormatProvider? provider);
Append(ulong value, string? format, IFormatProvider? provider);
Append(float value, string? format, IFormatProvider? provider);
Append(double value, string? format, IFormatProvider? provider);
Append(decimal value, string? format, IFormatProvider? provider);
//Those are completely new
Append(DateTime value, string? format = null, IFormatProvider? provider = null);
Append(DateTimeOffset value, string? format = null, IFormatProvider? provider = null);
Append(TimeSpan value, string? format = null, IFormatProvider? provider = null);
Append(Guid value, string? format = null);

Usage Examples

StringBuilder sb = new(64);
sb.Append(DateTime.Today, "yyyy-MM-dd", CultureInfo.InvariantCulture);
sb.Append(double.Epsilon, null, CultureInfo.InvariantCulture);

Alternative Designs

Alternatively only format and IFormatProvider parameters with default null value can be added to existing Append methods but this would be breaking change probably.
Still overloads for DateTime, DateTimeOffset, TimeSpan and Guid need to be added.

Risks

More code unless using alternative design.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions