Proposal: Adding TryFormat to IFormattable as a default interface method #30547
Labels
api-needs-work
API needs work before it is approved, it is NOT ready for implementation
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-System.Runtime
Milestone
Related: https://github.com/dotnet/corefx/issues/30114 (Discussion about introducing a new interface that has TryFormat)
Rationale
TryFormat
is as a less-allocating alternative ofToString
, which helps us reduce heap allocations by using provided reusable buffers instead of creating a new immutable string every time by callingToString
. However, since it isn't part of any interface/classes, there is no way that people can use it in APIs without hard-coding the type which are known to haveTryFormat
.Now that we have Default Interface Methods added to C# 8 (and having it supported in .NET Standard 2.1+ / .NET Core 3.0+), I think it would be great if we can add
TryFormat
toIFormattable
interface as a default interface method, that falls back to the implementation ofToString
if not implemented. The allocation caused by fallback if not implemented wouldn't likely be an issue, since there would be no alternatives but to callToString
, which would allocate the same amount of memory. Also, it seems pretty obvious that the behaviour ofTryFormat
when passed the same format/content should be the same as the one from equivalentToString
call, so callingToString
as a fallback would make sense.Proposed API
There is no implementations given in this proposal; However it would be very trivial, calling
ToString
then attempting to copy the contents of the returned string into the providedSpan
.Questions
Would it be worth making
format
andprovider
parameters optional for occasions when you just want it to return whatever is the default, given that there isn't a parameter-lessTryFormat
unlikeobject.ToString
?The text was updated successfully, but these errors were encountered: