I'm thinking of this a lot like MVVM one way binding in AngularJS. I have an object (a "model") with a few properties and a few methods - something like
{
"firstName": "John",
"lastName": "Doe",
"random": () => Random.Next(),
"formatDate": (fmt, value) => new DateTime(value).ToString(fmt)
}
I'd like to define a format string which can access values from the model or call methods from it and get back the formatted string. In AngularJS I would use an expression like this
Hello {firstName} {lastName}. Today is {formatDate('d', new Date())}.
Is there a way to do something similar in C# (.NET 5)? I'm looking to do this on strings.
Here are the ideas I've come up with and the problems with them
- WPF / XAML. This is a ton of overhead I don't care about. I only want to format
strings. - Roslyn. This requires me to write the format expressions as valid C#. It's also a lot of work.
- Formattable strings / ICustomFormatter. This doesn't have support for passing a dynamic model or for method calls.
EDIT
Here's a sample of what the calling code might look like
var formatString = person.Tenant.WelcomeMessageFormat;
var model = new
{
FirstName = person.FirstName,
LastName = person.LastName,
Random = () => Random.Next(),
FormatDate = (fmt, value) => new DateTime(value).ToString(fmt)
};
var message = ParseFormatString(formatString, model);
SendMessage(message);
// .....
public string ParseFormatString(string format, object model)
{
// what goes here?
}