Support named constants as format specifiers in interpolated strings #9779
Replies: 2 comments 5 replies
-
|
The following code compiles and runs without exceptions today: DateTime date = DateTime.Now;
var text = $"The date is {date:MyCustomDateFormat}";Imagine for instance if the code that was used was |
Beta Was this translation helpful? Give feedback.
-
|
With the suggested syntax of DateTime date = DateTime.Now;
const int padTo = 10;
FormattableString x = $"...{date,padTo:d}...";The compiler (following the spec) emits the code for this as: FormattableStringFactory.Create("...{0,10:d}...", new object[] { date });The compiler would have to start emitting code that builds the format string dynamically in these scenarios if the alignment component or formatting component were allowed to be non-constant. Interpolated string handlers are already set up in a way that would naturally handle non-constant alignment and formatting. The compiler emits a call to AppendFormatted (e.g. https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.defaultinterpolatedstringhandler.appendformatted) whose arguments naturally accept non-constant values. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
It would be nice if we could do something like:
As right now we must do either
var text = $"The date is {date.ToString(MyCustomDateFormat)}";which leads to needless allocation; or we have to forgo constant usage:var text = $"The date is {date:yyyyMMdd}";Maybe this can be extended even to fields or even arbitrary string-typed expressions.
EDIT: I realize now that the current syntax cannot be reused due to possible breaking changes and ambiguities as per @jnm2 example. But the feature request still stands. It would need a different syntax - perhaps
a doubleputting it inside of another::instead of a single:{ }like$"The date is {date:{MyCustomDateFormat}}"as was suggested by @mattwar ?Beta Was this translation helpful? Give feedback.
All reactions