Is there a way to specify ToUpper
or ToLower
when formatting data in an interpolated string
?
#98012
-
I want to print today's date in the format var output = $"Today is {DateTime.Now:d MMM yyyy}.";
Console.WriteLine(output); Assuming today's date is January 1st, 2024, the expected output of the above snippet is:
However, I have an added requirement that I want to display this in uppercase, but that currently (to my knowledge) requires manual invocations of var output = $"Today is {DateTime.Now.ToString("d MMM yyyy".ToUpper()}.";
Console.WriteLine(output); This achieves the desired effect, but I can't help but feel like this is something that would have support without those manual invocations. Is there a way to specify Important I'm not looking to format the entire
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 7 replies
-
Are you trying to avoid allocations? Ie this path is very hot. |
Beta Was this translation helpful? Give feedback.
-
Looks like you could create an instance of |
Beta Was this translation helpful? Give feedback.
-
Another option (which is a bit more involved since I believe it doesn't work nicely with string interpolation) would be:
Then just pick whatever method you like to copy the contents of the buffer into your final string (the real minimal-alloc way is |
Beta Was this translation helpful? Give feedback.
-
@tacosontitan check my question You can use the same approach to build ToUpper for every object and to use it in interpolated strings. |
Beta Was this translation helpful? Give feedback.
That's a no, sadly. My other answer would work for anything
ISpanFormattable
if you're willing to change from interpolation to like aStringBuilder
or something, or just live with the intermediate allocation.