Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Interpolation With Variable Content in C#

Tags:

c#

.net

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.

like image 501
Tony Lugg Avatar asked Apr 08 '17 00:04

Tony Lugg


People also ask

What is variable interpolation in C?

In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.

How do you add in string interpolation?

An interpolated verbatim string starts with the $ character followed by the @ character. Starting with C# 8.0, you can use the $ and @ tokens in any order: both $@"..." and @$"..." are valid interpolated verbatim strings. To include a brace, "{" or "}", in a result string, use two braces, "{{" or "}}".

What is the correct syntax for string interpolation?

Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.

Can we use expressions Inside string interpolation?

The string interpolation result is 'Hello, World!' . You can put any expression inside the placeholder: either an operator, a function call, or even more complex expressions. ${n1 + n2} is a placeholder consisting of the addition operator and 2 operands.


2 Answers

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:

"Hi {0}"

Then, when you retrieve the string template from the db, you can write:

var template = "Hi {0}"; //retrieved from db
var name = "Joe";
var result = string.Format(template, name);
//now result is "Hi Joe"

With 2 parameters:

var name2a = "Mike";
var name2b = "John";
var template2 = "Hi {0} and {1}!"; //retrieved from db
var result2 = string.Format(template2, name2a, name2b);
//now result2 is "Hi Mike and John!"

Alternative 2: use a placeholder.

You can store in your database something like this:

"Hi {name}"

Then, when you retrieve the string template from the db, you can write:

var template = "Hi {name}"; //retrieved from db
var name = "Joe";
var result = template.Replace("{name}", name);
//now result is "Hi Joe"

With 3 parameters:

var name2a = "Mike";
var name2b = "John";
var template2 = "Hi {name2a} and {name2b}!"; //retrieved from db
var result2 = template2
    .Replace("{name2a}", name2a)
    .Replace("{name2b}", name2b);
//now result2 is "Hi Mike and John!"

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.

like image 54
Massimiliano Kraus Avatar answered Sep 21 '22 05:09

Massimiliano Kraus


This can be done as requested using dynamic compilation, such as through the Microsoft.CodeAnalysis.CSharp.Scripting package. For example:

var name = "Joe";
var template = "Hi {name}";
var result = await CSharpScript.EvaluateAsync<string>(
    "var name = \"" + name + "\"; " +
    "return $\"" + template + "\";");

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.

like image 37
Douglas Avatar answered Sep 19 '22 05:09

Douglas