Can one store the template of a string in a variable and use interpolation on it?
var name = "Joe";
var template = "Hi {name}";
I then want to do something like:
var result = $template;
The reason is my templates will come from a database.
Can one store the template of a string in a variable and use interpolation on it?
var name = "Joe";
var template = "Hi {name}";
I then want to do something like:
var result = $template;
The reason is my templates will come from a database.
This can be done as requested using dynamic compilation, such as through the
Microsoft.CodeAnalysis.CSharp.Scripting
package. For example:Note that this approach is slow, and you'd need to add more logic to handle escaping of quotes (and injection attacks) within strings, but the above serves as a proof-of-concept.
I guess that these strings will have always the same number of parameters, even if they can change. For example, today
template
is"Hi {name}"
, and tomorrow could be"Hello {name}"
.Short answer: No, you cannot do what you have proposed.
Alternative 1: use the string.Format method.
You can store in your database something like this:
Then, when you retrieve the string template from the db, you can write:
With 2 parameters:
Alternative 2: use a placeholder.
You can store in your database something like this:
Then, when you retrieve the string template from the db, you can write:
With 3 parameters:
Pay attention at which token you choose for your placeholders. Here I used surrounding curly brackets
{}
. You should find something that is unlikely to cause collisions with the rest of your text. And that depends entirely on your context.No you can't do that since it needs
name
value at the time string is created (compile time). Consider usingString.Format
orString.Replace
instead.