thwd thwd - 1 year ago 71
C# Question

C# variables in 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
but I want to know if it can be done without calling a function/method on the string.

Answer Source

This functionality is not built-in to C#.

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!