Using variables inside strings
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.
Use the following methods
1: Method one
var count = 123;
var message = $"Rows count is: {count}";
2: Method two
var count = 123;
var message = "Rows count is:" + count;
3: Method three
var count = 123;
var message = string.Format("Rows count is:{0}", count);
4: Method four
var count = 123;
var message = @"Rows
count
is:{0}" + count;
5: Method five
var count = 123;
var message = $@"Rows
count
is: {count}";
This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.
The recommended way to do this would be with String.Format
:
string name = "Scott";
string output = String.Format("Hello {0}", name);
However, I wrote a small open-source library called SmartFormat that extends String.Format
so that it can use named placeholders (via reflection). So, you could do:
string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".
Hope you like it!