Reputation: 387
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#}" + ")});"
Upvotes: 1
Views: 523
Reputation: 2311
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 "}}".
var variable = 10;
var code = $"(function() {{ var myVariable = {variable} }});";
Console.WriteLine(code);
Output:
(function() { var myVariable = 10 });
Upvotes: 6
Reputation: 9509
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} }});";
Upvotes: 0
Reputation: 6511
Have you tried:
string someVariable = "test";
string code = $"(function()'{{var myvariable = ({someVariable} in c#)}});"
Using $ in C# is string interpolation. Added in C# 6
Upvotes: 0