AwkwardCoder
AwkwardCoder

Reputation: 25631

How to encode doube quotes when using CSharpSyntaxTree.ParseText (Roslyn)

I am trying to use the Roslyn compiler to dynamically generate an assembly & class.

When I call Emit I get and error about the double quoted value in the base constructor in the following:

How should I encode the double-quotes in the string I pass to ParseText?

var syntaxTree = CSharpSyntaxTree.ParseText(@"using System;
            using System.Linq;
            using Xxx.Operators;

            namespace Xxx.Operators
            {
                public sealed class DuplicateOperator : Operator
                {
                    public DuplicateOperator() : base(\""Sub\"")
                    {
                    }

                    public override long Execute(params Func<long>[] operands)
                    {
                        var firstValue = operands.First()() * 2;
                        return operands.Aggregate(firstValue, (a, b) => a - b());
                    }
                }
            }");

The error is generated when Emit is called in the following code, if I replace the qoted value (Sub) above with something like String.Empty then the Emit is successful.

var references = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic)
                .Select(a => a.Location)
                .Distinct()
                .Select(l => MetadataReference.CreateFromFile(l))
                .ToArray();

            var compilation = CSharpCompilation.Create("Xxx.DynamicOperator", new []{syntaxTree}, references,  new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

            using var ms = new MemoryStream();
            var result = compilation.Emit(ms);
            if (result.Success)
            {
                ms.Seek(0, SeekOrigin.Begin);
                Assembly assembly = Assembly.Load(ms.ToArray());
            }

Upvotes: 1

Views: 138

Answers (1)

Guru Stron
Guru Stron

Reputation: 142288

Double double quotes are used to represent a double quote in a verbatim string:

Only a quote escape sequence ("") is not interpreted literally; it produces one double quotation mark

So you should just remove \:

@"
....
public DuplicateOperator() : base(""Sub"")
...
"

Upvotes: 2

Related Questions