I want to interpolate not only the tokens in a string, but also the format itself. Here's an example using string.Format which loads the format string from a local variable:
object boxedDate = DateTime.Today;
var dateFormat = "MM-dd-yyyy";
var dateString = string.Format($"{{0:{dateFormat}}}", boxedDate);
With the interpolated string syntax, though, it seems that the format portion of the string is purely literal. Conceptually, I'd like to do something like this:
dateString = $"{boxedDate:{dateFormat}}";
Doesn't work, of course. I know that I could unbox the datetime and invoke .ToString() like this:
dateString = $"{((DateTime)boxedDate).ToString(dateFormat)}";
...but that requires me to know the type at runtime. This could be a decimal, integer, date, etc.
It's not a deal breaker or anything. I could always still use string.Format if there's no actual way to do this with interpolated string syntax.
I think there's no escaping knowing the type to select the appropriate format--or some conversion logic. The FormattableString type may help your cause a little though.
var lcid = "en-US";
FormattableString f = $"{model.Date:D}";
var s = f.ToString(new CultureInfo(lcid));
In this case I'm letting the system adjust the display format based on the culture info. You have to know about the type or convert the value beforehand, of course.
Other than that, yes, I think the ToString and string.Format methods are your best bet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With