Insert variable values in the middle of a string
There's now (C# 6) a more succinct way to do it: string interpolation.
From another question's answer:
In C# 6 you can use string interpolation:
string name = "John"; string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
String.Format("Hi We have these flights for you: {0}. Which one do you want",
flights);
EDIT: you can even save the "template" string separately (for instance you could store it in a configuration file and retrieve it from there), like this:
string flights = "Flight A, B,C,D";
string template = @"Hi We have these flights for you: {0}. Which one do you want";
Console.WriteLine(String.Format(template, flights));
EDIT2: whoops, sorry I see that @DanPuzey had already suggested something very similar to my EDIT (but somewhat better)
Use String.Format
Pre C# 6.0
string data = "FlightA, B,C,D";
var str = String.Format("Hi We have these flights for you: {0}. Which one do you want?", data);
C# 6.0 -- String Interpolation
string data = "FlightA, B,C,D";
var str = $"Hi We have these flights for you: {data}. Which one do you want?";
http://www.informit.com/articles/article.aspx?p=2422807
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.