4

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.