Search code examples
c#string-interpolation

Interpolation in the middle of a string


I want to interpolation in the middle of a string, but I cannot use String.Format, because the string contains {} curly brackets.

This is what I have tried so far:

string code = "(function(){var myvariable = $"{variableToBeInterpolated}"});"

Returns: ) expected ; expected

Edit: I tried the following snippet, the interpolation is now working, but the code is not executed in the browser.

"(function(){var myvariable=" + $"{myvariable c#}" + ")});"

Solution

  • General Information

    With C# version 6, extensive string interpolation capabilities have been added to the language.

    String interpolation provides a more readable and convenient syntax to create formatted strings than a string composite formatting feature.

    To solve your problem, please have a look at the special characters section of the documentation, which reads the following:

    To include a brace, "{" or "}", in the text produced by an interpolated string, use two braces, "{{" or "}}".


    Example

    var variable = 10;
    var code = $"(function() {{ var myVariable = {variable} }});";
    Console.WriteLine(code);
    

    Output: (function() { var myVariable = 10 });