'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 1:[1]

Have you tried:

string someVariable = "test";

string code = $"(function()'{{var myvariable = ({someVariable} in c#)}});"

Using $ in C# is string interpolation. Added in C# 6

docs.microsoft.com

Solution 2:[2]

Why do you want to interpolate in the middle, rather put $ in front. And for { you need to use {{. (the same applies for })

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2