Why doesn't BCL have methods like DateTime.WriteTo(TextWriter)
etc.
#116094
-
When calling It would be much more efficient to have: interface IAppendString
{
void AppendTo(StringBuilder sb); // whatever parameters/overloads are needed here for format, culture etc.
}
struct DateTime : ..., IAppendString
{
public void AppendTo(StringBuilder sb)
{
// ...
}
}
class StringBuilder // similar for TextWriter
{
public void Append<T>(T value) where T : IAppendString
{
value.AppendTo(this);
}
}
var sb = new StringBuilder();
sb.Append(DateTime.Now); // no allocations (other than potential char[] manipulations inside StringBuilder itself) This approach can be applied to all types - primitives like |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
This is against layering. Data types are core while This lead to the current solution: interpolated string handler with |
Beta Was this translation helpful? Give feedback.
This is against layering. Data types are core while
TextWriter
is at a higher layer. Efficiently writing toTextWriter
isn't special than writing to other things: just format the object into a buffer of UTF-8 or UTF-16, then copy the buffer to any writer. Or, just format to the destination buffer directly.This lead to the current solution: interpolated string handler with
IFormattable
/IUtf8Formattable
.StringBuilder
already implements this scheme.