1

I'm working on a system that gets templates from a database, then fills in values programmatically:

//using System.Runtime.CompilerServices;

var template = "Hello {0}"; // this string comes from the database
var name = "Joe";
var message = FormattableStringFactory.Create(template, new object[] { name });
Console.WriteLine(message);

This code sample works, but I can only use the numeric notation. I'd like to store the templates in the database in the interpolated string format, like this:

var template = "Hello {name}";

This throws a Run-time exception (line __): Input string was not in a correct format.

Is it possible to create an interpolated string from a string?

2
  • String interpolation is just syntax sugar. I am not sure about your needs, but did you think about this scenario ? 1.) know what tokens/ placeholders you have in template; 2.) Pass template, found tokens, data packed in Dictionary<Token, TokenValue> into factory 3.) Iterate over found tokens and replace placeholders template.Replace(tokenItem, tokensData[tokenItem].Value) Commented May 20, 2019 at 15:17
  • Both approaches share the same problem for human edits: if it's multiple indexes, then human can screw up with numbers; if it's name, then human may screw up with letter and type it as nmae. I'd keep using old good {0} and will simply split long ones into several simpler, e.g. instead of "Good day {0}, would you like to do {1}" I'd make two sentences. And, well, you can still screw up even with {0}. Commented May 20, 2019 at 15:52

1 Answer 1

0

I do something similar in a (probably) weird way.... but it works so i try to share with you my conclusion:

public static string ExtendedStringFormat(this string source, List<Tuple<string, string>> values)
    {
        string returnvalue = source;
        foreach(Tuple<string, string> my_touple in values)
        {
            returnvalue = returnvalue.Replace(string.Concat('{', my_touple.Item1, '}'), my_touple.Item2);
        }
        return returnvalue;
    }

And you can call it like below:

            List<Tuple<string, string>> lst =  new List<Tuple<string,string>>();
            lst.Add(new Tuple<string, string>("test","YAYYYYYY"));
            lst.Add(new Tuple<string, string>("test2","YAYYYYYY22222222"));
            string ret = "hem... hi? {test}, {test2}";
            ret = ret.ExtendedStringFormat(lst);
Sign up to request clarification or add additional context in comments.

2 Comments

The current implementation uses string.Replace, which is what we're trying to avoid.
Ok, sorry that my answer not helping you :( Btw what you not like of string.Replace()? Is mutch fast and memory efficient that many alternatives.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.