How do I interpolate strings?
I want to do the following in C# (coming from a Python background):
strVar = "stack"
mystr = "This is %soverflow" % (strVar)
How do I replace the token inside the string with the value outside of it?
This has been added as of C# 6.0 (Visual Studio 2015+).
Example:
var planetName = "Bob";
var myName = "Ford";
var formattedStr = $"Hello planet {planetName}, my name is {myName}!";
// formattedStr should be "Hello planet Bob, my name is Ford!"
This is syntactic sugar for:
var formattedStr = String.Format("Hello planet {0}, my name is {1}!", planetName, myName);
Additional Resources:
String Interpolation for C# (v2) Discussion
C# 6.0 Language Preview
string mystr = string.Format("This is {0}overflow", strVar);
And you could also use named parameters instead of indexes.
You can use string.Format
to drop values into strings:
private static readonly string formatString = "This is {0}overflow";
...
var strVar = "stack";
var myStr = string.Format(formatString, "stack");
An alternative is to use the C# concatenation operator:
var strVar = "stack";
var myStr = "This is " + strVar + "overflow";
If you're doing a lot of concatenations use the StringBuilder
class which is more efficient:
var strVar = "stack";
var stringBuilder = new StringBuilder("This is ");
for (;;)
{
stringBuilder.Append(strVar); // spot the deliberate mistake ;-)
}
stringBuilder.Append("overflow");
var myStr = stringBuilder.ToString();
If you currently use Visual Studio 2015 with C# 6.0, try the following:
var strVar = "stack";
string str = $"This is {strVar} OverFlow";
that feature is called string interpolation.