Insert variable values in the middle of a string

c#, string

Solution

You can use `string.Format`:

string template = "Hi We have these flights for you: {0}. Which one do you want";
string data = "A, B, C, D";
string message = string.Format(template, data);

You should load `template` from your resource file and `data` is your runtime values.

Be careful if you're translating to multiple languages, though: in some cases, you'll need different tokens (the `{0}`) in different languages.

Problem

In C#: If I want to create a message like this: "Hi We have these flights for you: Flight A,B,C,D. Which one do you want" where just the section in bold is dynamic and I pass its value at run time, but its left and right parts are fixed. I can create something like LeftMessage + those variables + RightMessage to create this. But I was wondering if there is a way of doing it all at once without the need to create two separate left and right messages? For translation purposes I am putting those left and right messages inside string resources so now I have two separate string resources. Is there a way to do it all at once?

Original source

Related problems