Slinidy
Slinidy

Reputation: 387

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#}" + ")});"

Upvotes: 1

Views: 523

Answers (3)

prd
prd

Reputation: 2311

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 });

Upvotes: 6

Johnny
Johnny

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

nick gowdy
nick gowdy

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

learn.microsoft.com

Upvotes: 0

Related Questions