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

2
  • Oh sorry that was a typo, because there's no code variable, the code' is method's parameter, let me fix the question. Commented Oct 15, 2020 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 Commented Oct 15, 2020 at 21:39

1 Answer 1

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}
        }}
    }}
}}";
Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.