I want to do the following in C# (coming from a Python background):
strVar = \"stack\"
mystr = \"This is %soverflow\" % (strVar)
How do I
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
Basic example:
var name = "Vikas";
Console.WriteLine($"My name is {name}");
Adding Special characters:
string name = "John";
Console.WriteLine($"Hello, \"are you {name}?\", but not the terminator movie one :-{{");
//output-Hello, "are you John?", but not the terminator movie one :-{
Not just replacing token with value, You can do a lot more with string interpolation in C#
Evaluating Expression
Console.WriteLine($"The greater one is: { Math.Max(10, 20) }");
//output - The greater one is: 20
Method call
static void Main(string[] args)
{
Console.WriteLine($"The 5*5 is {MultipleByItSelf(5)}");
}
static int MultipleByItSelf(int num)
{
return num * num;
}
Source: String Interpolation in C# with examples
You can accomplish this with Expansive: https://github.com/anderly/Expansive
There's one more way to implement placeholders with string.Replace, oddly helps in certain situations:
mystr = mystr.Replace("%soverflow", strVar);
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.
There is no operator for that. You need to use string.Format.
string strVar = "stack";
string mystr = string.Format("This is {0}soverflow", strVar);
Unfortunately string.Format
is a static method, so you can't simply write "This is {0}soverflow".Format(strVar)
. Some people have defined an extension method, that allows this syntax.