Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using variables inside strings

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.

like image 738
thwd Avatar asked Aug 29 '11 07:08

thwd


People also ask

How do you use a variable inside a string in Python?

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.

How do you declare a variable in a 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).

How do you add a variable to a string in Java?

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.


1 Answers

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.

like image 122
Fenton Avatar answered Oct 06 '22 00:10

Fenton