Search code examples
c#string-interpolation

Dollar sign doesn`t interpolate brackets in c#


I'm trying to create a string with the c# feature which uses the $ ( dollar sign ). The outcome would be like this {{name}}. The only thing I capture si the name and then I want to do something like E.G

$"{{name}}"

So my question is how to capture the whole thing? including brackets in a string? E.G "{{name}}"? It seems that I cannot do that with the $ sign.

This is what I tried

emailHtmlBuilder.Replace($"{{paramsHtml.Name}}", HttpUtility.HtmlEncode(paramsHtml.Value))};

The template has some placeholders E.G {{thisIsPlaceholder}}. And I want to replace the whole thing {{thisIsPlaceholder}} with E.G cup

Or shall I use regex in order to create that string?


Solution

  • You probably want $"{{{{{paramsHtml.Name}}}}}".

    The first and second {{ are the escape characters for a literal {, and the final { is the start of a placeholder in the interpolated string. Likewise the }'s.

    However, it's probably clearer to write "{{" + paramsHtml.Name + "}}" at this point -- it compiles to the same thing, in this case.