0

I'm trying to add some code to a code string like this


        public static string Compile(string code)
        {
            Write("compiler called.");
/////////////Below is the string I want to interpolate//////////////
            
            string codeToCompile = $@"
            using System;

            namespace RoslynCompileSample
            {
                public class Writer
                {
                    public string Write()
                    {
                        
                        {code}
                    }
                }
            }";
///////////////// Other Codes...//////////////////////////

I've tried to use $@ but still not recognized as a string:enter image description here

Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Leslie Gao
  • 143
  • 2
  • 12
  • Oh sorry that was a typo, because there's no `code` variable, the `code`' is method's parameter, let me fix the question. – Leslie Gao Oct 15 '20 at 21:32
  • Why are you using an interpolated string? You don't appear to need interpolation for this string and the fact that C# contains { } naturally as part of its scoping means it breaks the interpolation you have no need for – Caius Jard Oct 15 '20 at 21:39

1 Answers1

2

There are two things to mention here:

  1. Assignment of code is done incorrectly

  2. You have to escape the { and } characters within the interpolated string (Read the special characters section of the docs)
    (if you want to use a " too (in an verbatim string with @, you have also double it to "" to get one), e.g. string code = @"Console.WriteLine(""Helloworld"");";

string code = "Console.WriteLine(\"Helloworld\");";
string codeToCompile = $@"using System;

namespace RoslynCompileSample
{{
    public class Writer
    {{
        public string Write()
        {{
            var code = {code}
        }}
    }}
}}";
kapsiR
  • 2,720
  • 28
  • 36
  • See also [How to use escape characters with string interpolation in C# 6?](https://stackoverflow.com/q/31333096/1043380) – gunr2171 Oct 15 '20 at 21:37