Search code examples
c#string-interpolation

String concatenation using String interpolation


I've something like below.

var amount = "$1,000.99";
var formattedamount = string.Format("{0}{1}{0}", "\"", amount);

How can I achieve same using String interpolation?

I tried like below

var formattedamount1 = $"\"{amount}\"";

Is there any better way of doing this using string interpolation?


Solution

  • Update

    Is there any better way of doing this using string interpolation

    No, this is just string interpolation, you cant make the following any shorter and more readable really

    var formattedamount1 = $"\"{amount}\"";
    

    Original answer

    $ - string interpolation (C# Reference)

    To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}". For more information, see Escaping Braces.

    Quotes are just escaped as normal

    Example

    string name = "Horace";
    int age = 34;
    
    Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
    Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
    

    Output

    He asked, "Is your name Horace?", but didn't wait for a reply :-{
    Horace is 34 years old.