DarkNightFan DarkNightFan - 3 months ago 9
C# Question

Insert variable values in the middle of an string

In C#: If I want to create a message like this:
"Hi We have these flights for you: FlightA, B,C,D. Which one do you want"

where just the section in bold is dynamic and I pass its vale at run time, but its left and right part 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 purposese I am putting those left and right messages inside string resources so now I have two separate string resource. So I wanted to see if there is a way to do it all at once?

Answer

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.

Comments