In PHP I can do the following:
$name = 'John'; $var = "Hello {$name}"; // => Hello John
Is there a similar language construct in C#?
I know there is String.Format();
but I want to know if it can be done without calling a function/method on the string.
If you can depend on having Python >= version 3.6, then you have another attractive option, which is to use the new formatted string literal (f-string) syntax to insert variable values. An f at the beginning of the string tells Python to allow any currently valid variable names as variable names within the string.
To declare and initialize a string variable: Type string str where str is the name of the variable to hold the string. Type ="My String" where "My String" is the string you wish to store in the string variable declared in step 1. Type ; (a semicolon) to end the statement (Figure 4.8).
Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With